关于如何上传大图片文件到后台,以及后台接收处理保存到数据库

这次移动项目中有需要上传头像的需求【众所周知,手机自行拍摄的图片都很大】所以导致,上传慢加载慢的问题,先看看如何上传图片

weui.js下载

前台代码:

注意点: input标签中的属性 accept和type

前台脚本:

var fileArr = new Array();
        $(function () {
            var $uploaderInput = $("#uploaderInput"); //上传按钮+
            $uploaderInput.on("change", function (e) {
                fileArr.splice(0, fileArr.length);
                var src, url = window.URL || window.webkitURL || window.mozURL, files = e.target.files;
                if (url) {
                    src = url.createObjectURL(files[0]);
                } else {
                    src = e.target.result;
                }
                $("#patientHeadPortrait").attr("src", src);
                fileArr.push(files[0]);
                update(fileArr);
            });
        });
        function update(e) {
            var formData = new FormData();
            formData.append("patientId", '<%=patientId%>');
            for (var i = 0; i < e.length; i++) {
                formData.append("file[]", e[i]);
            }
            formData.append("method", "UpdatePatientHeadPortrait");

            $.ajax({
                url: "ashx/MyOrderHandler.ashx",
                type: "post",
                async: false,
                cache: false,
                processData: false,// 告诉jQuery不要去处理发送的数据
                contentType: false,// 告诉jQuery不要去设置Content-Type请求头
                data: formData,
                success: function (data) {

                },
                error: function (error) {
                }
            });
        }

由于项目使用框架比较老旧,后台使用一般处理程序接收前台数据:

public void ProcessRequest(HttpContext context)
    {
        if (context.Request["method"] != null)
        {
            this.GetType().GetMethod(context.Request["method"]).Invoke(this, new object[] { context });
        }
    }

public void UpdatePatientHeadPortrait(HttpContext context)
    {
        HttpFileCollection fileslist = context.Request.Files;
        string PatientId = context.Request["patientId"];
        string base64Str = string.Empty;
        if (fileslist.Count > 0)
        {
            for (int i = 0; i < fileslist.Count; i++)
            {
                HttpPostedFile img = fileslist.Get(i);
                base64Str = OcOrderService.CreateThumbnail(img);
            }
        }
        ocUserService.UpdatePatientHeadPortTrait(PatientId, base64Str);
    }

其中,大图片处理使用到了这个方式:

/// 
        /// 图片上传缩略图转base64
        /// 
        /// 
        /// 
        public static string CreateThumbnail(HttpPostedFile img)
        {
            System.Drawing.Image original_image = null;
            System.Drawing.Bitmap final_image = null;
            System.Drawing.Graphics graphic = null;
            MemoryStream ms = new MemoryStream();
            string base64img = "";
            try
            {
                original_image = System.Drawing.Image.FromStream(img.InputStream);
                int original_width = original_image.Width;//截取原图宽度
                int original_height = original_image.Height;//截取原图高度
                int t_width = Convert.ToInt32(original_width * 0.1);//缩略图宽度
                int t_heigght = Convert.ToInt32(original_height * 0.1);//缩略图高度
                if (original_width < 100)
                {
                    t_width = original_width;
                    t_heigght = original_height;
                }
                else if (original_width > 100 && original_width < 1000)
                {
                    t_width = Convert.ToInt32(original_width * 0.5);
                    t_heigght = Convert.ToInt32(original_height * 0.5);
                }
                else
                {
                    t_width = Convert.ToInt32(original_width * 0.1);
                    t_heigght = Convert.ToInt32(original_height * 0.1);
                }
                final_image = new System.Drawing.Bitmap(t_width, t_heigght);
                graphic = System.Drawing.Graphics.FromImage(final_image);

                graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; /* new way */
                graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                graphic.Clear(System.Drawing.Color.White);//背景
                System.Drawing.Rectangle SrcRec = new System.Drawing.Rectangle(0, 0, original_width, original_height);
                System.Drawing.Rectangle targetRec = new System.Drawing.Rectangle(0, 0, t_width, t_heigght);
                graphic.DrawImage(original_image, targetRec, SrcRec, System.Drawing.GraphicsUnit.Pixel);

                final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                base64img = "data:image/png;base64," + Convert.ToBase64String(arr);
            }
            catch(Exception ex)
            {
                LogHelper.Write("上传图片缩略图失败 " + ex.ToString());
            }
            finally
            {
                if (final_image != null) final_image.Dispose();
                if (graphic != null) graphic.Dispose();
                if (original_image != null) original_image.Dispose();
                if (ms != null) ms.Close();
            }
            return base64img;
        }

针对,0-1000尺寸和大于1000的图片处理进行缩略图片

这下加载和上传图片速度快很多,不足之处是大图片的清晰度会大大降低

你可能感兴趣的:(C#,webform,ajax,js,图片压缩,C#)