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

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

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



    
    


    
图片格式为.jpg, .gif, .bmp, .png
上传图片

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);
            }
        }

        /// 
        /// 验证是否指定的图片格式
        /// 
        /// 
        /// 
        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):
    /// 
    /// Handler1 的摘要说明
    /// 
    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中增加配置:
    
        
          
        
    



你可能感兴趣的:(Asp.net)