Asp.Net FileUpload选择图片后预览,并直接上传

文件上传预览与处理技术
本文介绍了一种实现文件上传功能的技术,包括文件预览、格式验证、上传过程及后端处理流程,通过JavaScript与ASP.NET技术实现,确保用户在上传图片前能够预览并选择合适的文件。

FileUpload选择图片后先预览图片,然后上传。

使用到FileUpload的onchange事件,及使用一般处理程序(.ashx)来预览图片。

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function uploadFile(filePath) {
            if (filePath.length > 0) {
                __doPostBack('btnUploadFile', '');
                formReset();
            }
        }
        function formReset() {
            document.getElementById("form1").reset()
        }
  </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Image ID="Image1" runat="server" ImageAlign="Middle" /></div>
        <div style="width:800px;margin:0 auto;visibility:hidden">
            <asp:FileUpload ID="FileUpload" runat="server" accept="image/*" onchange="uploadFile(this.value)"/>
        </div>
        <div style="width:800px;margin:0 auto;">图片格式为.jpg, .gif, .bmp, .png</div>
        <div style="width:800px;margin-top:10px; height: 16px; margin-left: auto; margin-right: auto; margin-bottom: 0;"><asp:Label ID="lbl_pic" 
            runat="server" ForeColor="#FFFF66" Font-Bold="True" Font-Italic="False" 
            Font-Overline="False"></asp:Label>
        </div>
        <div style="width:800px;margin:0 auto;">
            <button type="button" onclick="document.getElementById('FileUpload').click();">选择图片</button>
        </div>
        <div style="visibility:hidden">
            <asp:LinkButton ID="btnUploadFile" runat="server" onclick="btnUploadFile_Click">上传图片</asp:LinkButton>
        </div>
    </form>
</body>
</html>

formReset()防止上传后刷新页面重复提交。
        protected void btnUploadFile_Click(object sender, EventArgs e)
        {
            if (!this.FileUpload.HasFile)
            {
                lbl_pic.Text = "请选择要使用的照片!";
                return;
            }
            string fileExtension = Path.GetExtension(this.FileUpload.FileName).ToLower();
            if (!isImage(fileExtension))
            {
                lbl_pic.Text = "图片格式不对,请重新选择!";
                return;
            }
            Session["UploadBytes"] = this.FileUpload.FileBytes;
            this.Image1.ImageUrl = "~/ImagePreview.ashx"

            string imageName = Guid.NewGuid().ToString().Trim() + ".jpg";
            string virpath = "/temp/";
            if (!Directory.Exists(Server.MapPath(virpath)))
            {
                Directory.CreateDirectory(Server.MapPath(virpath));
            }
            string mappath = Server.MapPath(virpath + imageName);
            if ((Session["UploadBytes"]) != null)
            {
                byte[] buffer = (byte[])(Session["UploadBytes"]);
                File.WriteAllBytes(mappath, buffer);
            }
        }

        /// <summary>
        /// 验证是否指定的图片格式
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public bool isImage(string str)
        {
            bool isimage = false;
            string thestr = str.ToLower();
            string[] allowExtension = { ".jpg", ".gif", ".bmp", ".png" };
            for (int i = 0; i < allowExtension.Length; i++)
            {
                if (thestr == allowExtension[i])
                {
                    isimage = true;
                    break;
                }
            }
            return isimage;
        }

一般处理程序(ImagePreview.ashx):
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class ImagePreview : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            if ((context.Session["UploadBytes"]) != null)
            {
                byte[] buffer = (byte[])(context.Session["UploadBytes"]);
                context.Response.BinaryWrite(buffer);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

Web.config中增加配置:
    <system.web>
        <httpHandlers>
          <add verb="*" path="ImagePreview.ashx" type="命名空间.ImagePreview"/>
        </httpHandlers>
    </system.web>



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值