asp .net MVC 图片文件上传--关于限制图片数量、自动压缩等

在最近一个项目里,要求在上传图片的时候需要要求显示图片缩略图、上传图片数量限制、图片超过一定尺寸、一定的大小就自动进行压缩,最后要求同一个页面上传的文件必须拥有统一的GUID,以此来识别是同一个产品的所有图片。

MVC在上传图片这方面上做得非常的现代,可以通过用极简单的代码进行上传图片。图片压缩我是参考了网上的例程。该代码的原理是将大图片显示在canvas里面,再采用canvas.toDataURL的方法得到base64字符串来实现压缩。

弄清了原理以后,就可以进行js代码进行采样。这里我是参考了这篇博客,但我在实际使用中发现了一个BUG,导致上传时显示“参数无效”。而且由于控制器那里使用了try导致我一时半会不知错误是在那里,延误了开发进程,后来我根据我的需求重新写了这个js。

; (function () {
    function detectSubsampling(img) {
        var iw = img.naturalWidth, ih = img.naturalHeight;
        if (iw * ih > 1024 * 1024) { //大于百万像素的就会进行抽样
            var canvas = document.createElement('canvas');
            canvas.width = canvas.height = 1;
            var ctx = canvas.getContext('2d');
            ctx.drawImage(img, -iw + 1, 0);
            // subsampled image becomes half smaller in rendering size.
            // check alpha channel value to confirm image is covering edge pixel or not.
            // if alpha value is 0 image is not covering, hence subsampled.
            return ctx.getImageData(0, 0, 1, 1).data[3] === 0;
        } else {
            return false;
        }
    }

    /**
     * Detecting vertical squash in loaded image.
     * Fixes a bug which squash image vertically while drawing into canvas for some images.
     */
    function detectVerticalSquash(img, iw, ih) {
        var canvas = document.createElement('canvas');
        canvas.width = 1;
        canvas.height = ih;
        var ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0);
        var data = ctx.getImageData(0, 0, 1, ih).data;
        // search image edge pixel position in case it is squashed vertically.
        var sy = 0;
        var ey = ih;
        var py = ih;
        while (py > sy) {
            var alpha = data[(py - 1) * 4 + 3];
            if (alpha === 0) {
                ey = py;
            } else {
                sy = py;
            }
            py = (ey + sy) >> 1;
        }
        var ratio = (py / ih);
        return (ratio === 0) ? 1 : ratio;
    }

    /**
     * Rendering image element (with resizing) and get its data URL
     */
    function renderImageToDataURL(img, options, doSquash) {
        var canvas = document.createElement('canvas');
        renderImageToCanvas(img, canvas, options, doSquash);
        return canvas.toDataURL("image/jpeg", options.quality || 0.8);
    }

    /**
     * Rendering image element (with resizing) into the canvas element
     */
    function renderImageToCanvas(img, canvas, options, doSquash) {
        var iw = img.naturalWidth, ih = img.naturalHeight;
        if (!(iw + ih)) return;
        var width = options.width, height = options.height;
        var ctx = canvas.getContext('2d');
        ctx.save();
        transformCoordinate(canvas, ctx, width, height, options.orientation);
        var subsampled = detectSubsampling(img);
        if (subsampled) {
            iw /= 2;
            ih /= 2;
        }
        var d = 1024; // size of tiling canvas
        var tmpCanvas = document.createElement('canvas');
        tmpCanvas.width = tmpCanvas.height = d;
        var tmpCtx = tmpCanvas.getContext('2d');
        var vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1;
        var dw = Math.ceil(d * width / iw);
        var dh = Math.ceil(d * height / ih / vertSquashRatio);
        var sy = 0;
        var dy = 0;
        while (sy < ih) {
            var sx = 0;
            var dx = 0;
            while (sx < iw) {
                tmpCtx.clearRect(0, 0, d, d);
                tmpCtx.drawImage(img, -sx, -sy);
                ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh);
                sx += d;
                dx += dw;
            }
            sy += d;
            dy += dh;
        }
        ctx.restore();
        tmpCanvas = tmpCtx = null;
    }

    /**
     * Transform canvas coordination according to specified frame size and orientation
     * 根据帧的大小和方向调整canvas
     * 方向值是来自EXIF标签
     */
    function transformCoordinate(canvas, ctx, width, height, orientation) {
        switch (orientation) {
            case 5:
            case 6:
            case 7:
            case 8:
                canvas.width = height;
                canvas.height = width;
                break;
            default:
                canvas.width = width;
                canvas.height = height;
        }
        switch (orientation) {
            case 2:
                // horizontal flip
                ctx.translate(width, 0);
                ctx.scale(-1, 1);
                break;
            case 3:
                // 180 rotate left
                ctx.translate(width, height);
                ctx.rotate(Math.PI);
                break;
            case 4:
                // vertical flip
                ctx.translate(0, height);
                ctx.scale(1, -1);
                break;
            case 5:
                // vertical flip + 90 rotate right
                ctx.rotate(0.5 * Math.PI);
                ctx.scale(1, -1);
                break;
            case 6:
                // 90 rotate right
                ctx.rotate(0.5 * Math.PI);
                ctx.translate(0, -height);
                break;
            case 7:
                // horizontal flip + 90 rotate right
                ctx.rotate(0.5 * Math.PI);
                ctx.translate(width, -height);
                ctx.scale(-1, 1);
                break;
            case 8:
                // 90 rotate left
                ctx.rotate(-0.5 * Math.PI);
                ctx.translate(-width, 0);
                break;
            default:
                break;
        }
    }

    var URL = window.URL && window.URL.createObjectURL ? window.URL :
              window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL :
              null;

    /**
     * MegaPixImage class
     */
    function MegaPixImage(srcImage) {
        if (window.Blob && srcImage instanceof Blob) {
            if (!URL) { throw Error("No createObjectURL function found to create blob url"); }
            var img = new Image();
            img.src = URL.createObjectURL(srcImage);
            this.blob = srcImage;
            srcImage = img;
        }
        if (!srcImage.naturalWidth && !srcImage.naturalHeight) {
            var _this = this;
            srcImage.onload = srcImage.onerror = function () {
                var listeners = _this.imageLoadListeners;
                if (listeners) {
                    _this.imageLoadListeners = null;
                    for (var i = 0, len = listeners.length; i < len; i++) {
                        listeners[i]();
                    }
                }
            };
            this.imageLoadListeners = [];
        }
        this.srcImage = srcImage;
    }

    /**
     * Rendering megapix image into specified target element
     */
    MegaPixImage.prototype.render = function (target, options, callback) {
        if (this.imageLoadListeners) {
            var _this = this;
            this.imageLoadListeners.push(function () { _this.render(target, options, callback); });
            return;
        }
        options = options || {};
        var imgWidth = this.srcImage.naturalWidth, imgHeight = this.srcImage.naturalHeight,
            width = options.width, height = options.height,
            maxWidth = options.maxWidth, maxHeight = options.maxHeight,
            doSquash = !this.blob || this.blob.type === 'image/jpeg';
        if (width && !height) {
            height = (imgHeight * width / imgWidth) << 0;
        } else if (height && !width) {
            width = (imgWidth * height / imgHeight) << 0;
        } else {
            width = imgWidth;
            height = imgHeight;
        }
        if (maxWidth && width > maxWidth) {
            width = maxWidth;
            height = (imgHeight * width / imgWidth) << 0;
        }
        if (maxHeight && height > maxHeight) {
            height = maxHeight;
            width = (imgWidth * height / imgHeight) << 0;
        }
        var opt = { width: width, height: height };
        for (var k in options) opt[k] = options[k];
        target.tagName = target.tagName || "IMG";
        var tagName = target.tagName.toLowerCase();
        if (tagName === 'img') {
            target.src = renderImageToDataURL(this.srcImage, opt, doSquash);
        } else if (tagName === 'canvas') {
            renderImageToCanvas(this.srcImage, target, opt, doSquash);
        }
        if (typeof this.onrender === 'function') {
            this.onrender(target);
        }
        if (callback) {
            callback();
        }
        if (this.blob) {
            this.blob = null;
            URL.revokeObjectURL(this.srcImage.src);
        }
    };

    /**
     * Export class to global
     */
    if (typeof define === 'function' && define.amd) {
        define([], function () { return MegaPixImage; }); // for AMD loader
    } else if (typeof exports === 'object') {
        module.exports = MegaPixImage; // for CommonJS
    } else {
        this.MegaPixImage = MegaPixImage;
    }

})();

; (function ($) {
    $.extend($, {
        fileUpload: function (options) {
            var para = {
                multiple: true,
                filebutton: ".filePicker",
                uploadButton: null,
                url: "/me/MUploadImg",
                base64strUrl: "/me/MUploadImgBase64Str",
                filebase: "mfile",//mvc后台需要对应的名称
                auto: true,
                previewZoom: null,
                uploadComplete: function (res) {
                    console.log("uploadComplete", res);
                    uploadCount++;
                    core.checkComplete();
                },
                uploadError: function (err) {
                    console.log("uploadError", err);
                },
                onProgress: function (percent) {  // 提供给外部获取单个文件的上传进度,供外部实现上传进度效果
                    console.log(percent);
                },
            };
            para = $.extend(para, options);

            var $self = $(para.filebutton);
            //先加入一个file元素
            var multiple = "";  // 设置多选的参数
            para.multiple ? multiple = "multiple" : multiple = "";
            $self.css('position', 'relative');
            $self.append('');

            var doms = {
                "fileToUpload": $self.find("#fileImage"),
                // "thumb": $self.find(".thumb"),
                // "progress": $self.find(".upload-progress")
            };

            function getBase64Image(img) {
                var canvas = document.createElement("canvas");
                canvas.width = img.width;
                canvas.height = img.height;

                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, img.width, img.height);

                var dataURL = canvas.toDataURL("image/jpeg");
                return dataURL;

                // return dataURL.replace("data:image/png;base64,", "");
            }
            function simpleSize(size) {
                if (!size) return "0";
                if (size < 1024) {
                    return size;
                }
                var kb = size / 1024;
                if (kb < 1024) {
                    return kb.toFixed(2) + "K";
                }
                var mb = kb / 1024;
                if (mb < 1024) {
                    return mb.toFixed(2) + "M";

                }
                var gb = mb / 1024;
                return gb.toFixed(2) + "G";
            };
            //Convert DataURL to Blob to send over Ajax
            function dataURItoBlob(dataUrl) {
                // convert base64 to raw binary data held in a string
                // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
                var byteString = atob(dataUrl.split(',')[1]);

                // separate out the mime component
                var mimeString = dataUrl.split(',')[0].split(':')[1].split(';')[0];

                // write the bytes of the string to an ArrayBuffer
                var ab = new ArrayBuffer(byteString.length);
                var ia = new Uint8Array(ab);
                for (var i = 0; i < byteString.length; i++) {
                    ia[i] = byteString.charCodeAt(i);
                }
                return new Blob([ab], { type: 'image/jpeg' });
            }

            var uploadCount = 0;
            var core = {
                fileSelected: function () {
                    var files = $("#fileImage")[0].files;
                    var count = files.length;
                    
                    console.log("共有" + count + "个文件");
                    for (var i = 0; i < count; i++) {
                        if (i >= para.limitCount) {
                             imClient.customerSay("最多只能选择"+para.limitCount+"张图片!");
                            break;
                        }
                        var item = files[i];
                        console.log("原图片大小", item.size);

                        if (item.size > 1024 * 1024 * 1) {
                            console.log("图片大于1M,开始进行压缩...");

                            (function(img) {
                                var mpImg = new MegaPixImage(img);
                                var resImg = document.getElementById("resultImage");
                                resImg.file = img;
                                mpImg.render(resImg, { maxWidth: 500, maxHeight: 500, quality: 1 }, function() {
                                    var base64 = getBase64Image(resImg);
                                    var base641 = resImg.src;
                                    console.log("base641", base64.length, simpleSize(base64.length), base641.length, simpleSize(base641.length));
                                    if (para.auto) core.uploadBase64str(base641);
                                });
                            })(item);

                        } else {
                            if (para.auto) core.uploadFile(item);
                        }
                        core.previewImage(item);
                    }
                },
                uploadBase64str: function (base64Str) {
                    var guid = $("#guid0").val();
                    //var blob = dataURItoBlob(base64Str);
                    //console.log("压缩后的文件大小", blob.size);
                    //core.uploadFile(blob);
                    var formdata = new FormData();
                    formdata.append("base64str", base64Str);
                    formdata.append("guid", guid);
                    var xhr = new XMLHttpRequest();
                    xhr.upload.addEventListener("progress", function (e) {
                        var percentComplete = Math.round(e.loaded * 100 / e.total);
                        para.onProgress(percentComplete.toString() + '%');
                    });
                    xhr.addEventListener("load", function (e) {
                        para.uploadComplete(xhr.responseText);
                    });
                    xhr.addEventListener("error", function (e) {
                        para.uploadError(e);
                    });

                    xhr.open("post", para.base64strUrl, true);
                    xhr.send(formdata);
                },
                uploadFile: function (file) {
                    console.log("开始上传");
                    var guid = $("#guid0").val();
                    var formdata = new FormData();

                    formdata.append(para.filebase, file);//这个名字要和mvc后台配合
                    formdata.append("guid", guid);
                    var xhr = new XMLHttpRequest();
                    xhr.upload.addEventListener("progress", function (e) {

                        var percentComplete = Math.round(e.loaded * 100 / e.total);
                        para.onProgress(percentComplete.toString() + '%');
                    });
                    xhr.addEventListener("load", function (e) {
                        para.uploadComplete(xhr.responseText);
                    });
                    xhr.addEventListener("error", function (e) {
                        para.uploadError(e);
                    });

                    xhr.open("post", para.url, true);
                    xhr.send(formdata);
                },
                checkComplete:function() {
                    var all = (doms.fileToUpload)[0].files.length;
                    if (all == uploadCount) {
                        console.log(all + "个文件上传完毕");
                        doms.fileToUpload.remove();
                        //input有一个问题就是选择重复的文件不会触发change事件,所以做了一个处理,再每次上传完之后删掉这个元素再新增一个input。
                        $self.append('');

                    }
                },
                uploadFiles: function () {
                    var files = (doms.fileToUpload)[0].files;
                    for (var i = 0; i < files.length; i++) {
                        core.uploadFile(files[i]);
                    }
                },
                previewImage: function (file) {
                    if (!para.previewZoom) return;
                    var img = document.createElement("img");
                    img.file = file;
                    $(para.previewZoom).append(img);
                    // 使用FileReader方法显示图片内容
                    var reader = new FileReader();
                    reader.onload = (function (aImg) {
                        return function (e) {
                            aImg.src = e.target.result;
                        };
                    })(img);
                    reader.readAsDataURL(file);
                }
            }
            $(document).on("change", "#fileImage", function () {
                core.fileSelected();
            });

            $(document).on("click", para.filebutton, function () {
                console.log("clicked");
            });
            if (para.uploadButton) {
                $(document).on("click", para.uploadButton, function () {
                    core.uploadFiles();
                });
            }
        }
    });
})(jQuery);

在视图中,我用了最简单的页面进行调试:


@{
    Layout = null;
}



    


    h5图片压缩与上传
    


UploadImg

点击选择文件

ViewBag.uid是在控制器里面直接生成的,这里我为了调试方便,直接采用type="text" 进行赋值,在实际应用可以采用hidden。

下面是控制器的内容:

 public ActionResult Uptest()
        {
            ViewBag.uid = Guid.NewGuid();
            return View();
        }

        [HttpPost]
        public ActionResult MUploadImg(HttpPostedFileBase mfile,string guid)
        {
            return UploadImg(mfile,guid);
        }

        [HttpPost]
        public ActionResult UploadImg(HttpPostedFileBase file,string guid)
        {

            if (file != null)
            {
                var path = "~/uploads/";
                var uploadpath = Server.MapPath(path);
                if (!Directory.Exists(uploadpath))
                {
                    Directory.CreateDirectory(uploadpath);
                }
                string fileName = Path.GetFileName(file.FileName);// 原始文件名称
                string fileExtension = Path.GetExtension(fileName); // 文件扩展名
                string saveName = Guid.NewGuid() + fileExtension; // 保存文件名称 这是个好方法。
                //string saveName = Encrypt.GenerateOrderNumber() + fileExtension; // 保存文件名称 这是个好方法。
                file.SaveAs(uploadpath + saveName);

                return Json(new { Success = true, SaveName = path + saveName+' '+guid });
            }
            return Json(new { Success = false, Message = "请选择要上传的文件!" }, JsonRequestBehavior.AllowGet);

        }

        [HttpPost]
        public ActionResult MUploadImgBase64Str(string base64str, string guid)
        {
            
            var imgData = base64str.Split(',')[1];
            //过滤特殊字符即可   
            string dummyData = imgData.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+");
            if (dummyData.Length % 4 > 0)
            {
                dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '=');
            }
            byte[] byteArray = Convert.FromBase64String(dummyData);
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray))
            {
                Image img = Image.FromStream(ms);
                var path = "~/uploads/";
                var uploadpath = Server.MapPath(path);

                var saveName = uploadpath + "stoneniqiu" + ".jpg";
                img.Save(saveName);
                return Json(new { Success = true, SaveName = saveName+' '+guid });
            }

            }

在控制器中,我首先传递一个Guid 到视图,然后用AJAX提交,又回到控制器获取,这是为了生成一个唯一而又统一的Guid 。在真实应用中,这里是上传文件成功之后做一个写入数据库的动作,这里是为了测试,我仅仅让它在成功处输出,再到js用console.log 输出在浏览器中显示。

js文件的思路非常不错,提交文件以后,通过判断图像的大小进行处理,文件大于某个字节以后就采样在canvas里面显示,再通过canvas.toDataURL的方法得到base64字符串来实现压缩。前端压缩的好处是速度快。

你可能感兴趣的:(asp .net MVC 图片文件上传--关于限制图片数量、自动压缩等)