Uploadifive上传

因为项目需要,结合之前的项目使用的Uploadifive上传做了点小小的拓展。

 

var YSHT = (function ($, ysht) {
    ysht.UploadFiles = function (options) {
        var defaults = {
            element: "input[type='file']",
            auto: true,             //是否自动上传
            buttonText: "附件上传", //定义显示在按钮上的文本
            fileSizeLimit: "20GB",//上传文件大小限制
            uploadLimit: 999,       //上传文件个数
            width: 100,
            height:34,
            formData: {},
            callback: null,
            multi: false,
            url: "",
            removeCompleted:true
        };
        var opts = $.extend({}, defaults, options);
        if (!opts.url) {
            alert("初始化上传控件发生错误!");
            return false;
        }
        if (!$(opts.element).attr("id")) {
            alert("初始化上传控件发生错误!");
            return false;
        }
        var files = [];

        var uploadify = $(opts.element).uploadifive({
            auto: opts.auto,
            width: opts.width,
            height: opts.height,
            buttonClass: "btn btn-primary",
            buttonText: "<i class=\"fa fa-upload\"></i>&nbsp;&nbsp;" + opts.buttonText,
            dnd: false,           //禁用拖拽上传功能
            fileSizeLimit: opts.fileSizeLimit,
            fileType: true,      //允许所有的文件类型(允许所有图片'image/*') 
            method: "post",
            multi: opts.multi,
            removeCompleted: opts.removeCompleted,//是否移除从队列张完成上传的项目
            formData: opts.formData,
            uploadLimit: opts.uploadLimit,
            uploadScript: opts.url,
            onError: function (res) {
                alert(res.errMsg);
                return false;
            },
            onUploadComplete: function (file, res) {
            res = JSON.parse(res);
            var html = "<div class = 'img-view'><img class = 'previewImg previewImg_1' width='200' height='200' src=''";
            html += "serverFilePath = '" + res.FilePath + "'";
            html += "fileName = '" + res.FileName + "'";
            html += "fileExt='" + res.FileExt + "'/>";
            html += "<a class='img-del' del-path='" + res.FilePath + "'";
            html += "filename = '" + res.FileName + "'fileext='" + res.FileExt + "'>删除</a></div>";
            $("#preview").append(html)

            var imgArray = document.getElementById("preview").getElementsByTagName("img");
            var finallyImg = document.getElementById("preview").getElementsByTagName("img")[imgArray.length - 1];
            $(finallyImg).siblings('a').attr({ 'del-path': res.FilePath, "fileName": res.FileName, fileExt: res.FileExt });
            var reader = new FileReader();
            var path = res.SavePath;
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                url = reader.result;
                finallyImg.src = url;
                $("#resultImage")[0].src = url;
            };            }
        });
        //RETURN {
        //    uPLOADIFY: UPLOADIFY,
        //    fILES: FILES
        //};
    };
    return ysht;
}(jQuery, window.YSHT || {}));

 

后台代码分为压缩上传和不压缩上传,其中压缩上传的方法是在网上找了个大神写的。因为是改别人的代码,很多写的很乱地方没有改的完善,有空需要好好整理一下

        /// <summary>
        /// 未压缩上传
        /// </summary>
        /// <param name="mfile"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult NotCompressUploadImg(HttpPostedFileBase mfile)
        {
            try
            {
                if (mfile != null)
                {
                    string fileName = Path.GetFileName(mfile.FileName);// 原始文件名称
                    string fileExtension = Path.GetExtension(fileName); // 文件扩展名
                    string saveName = Guid.NewGuid() + fileExtension; // 保存文件名称 这是个好方法。
                    string savepath = Server.MapPath("../ImageTemp/") + fileName;
                    mfile.SaveAs(savepath);
                    if (IsPicture(savepath) == 1)
                    {
                        return Json(new { Success = false, Message = "该图发现木马文件!" }, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        var path = "/Upload/Image/";
                        var uploadpath = Server.MapPath("~" + path);
                        if (!Directory.Exists(uploadpath))
                        {
                            Directory.CreateDirectory(uploadpath);
                        }

                        //string saveName = Encrypt.GenerateOrderNumber() + fileExtension; // 保存文件名称 这是个好方法。
                        mfile.SaveAs(uploadpath + saveName);
                        var fullPath = uploadpath.Replace("\\", "/") + saveName;
                        return Json(new { Success = true, FilePath = path + saveName, FileName = fileName, FileExt = fileExtension, SavePath = fullPath, Message = "上传成功!" });
                    }
                }
                return Json(new { Success = false, Message = "请选择要上传的文件!" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
            }
            
        }

 

public ActionResult CompressImgBase64Uploadfinal(HttpPostedFileBase mfile)
        {
            try
            {
                if (mfile != null)
                {
                    //先保存到临时文件夹,如果是病毒,就删除s
                    string fileName = Path.GetFileName(mfile.FileName);// 原始文件名称
                    string fileExtension = Path.GetExtension(fileName); // 文件扩展名
                    string saveName = Guid.NewGuid() + fileExtension; // 保存文件名称 这是个好方法。
                    string savepath = Server.MapPath("../ImageTemp/") + fileName;
                    mfile.SaveAs(savepath);
                    var readpath = savepath.Replace("\\", "/");
                    System.Drawing.Image img = new System.Drawing.Bitmap(readpath);
                    if (IsPicture(savepath) == 1)
                    {
                        return Json(new { Success = false, FilePath = "", FileName = "", FileExt = ".jpg", Message = "上传的图片有病毒!" });
                    }
                    var path = "/Upload/Image/";
                    var uploadpath = Server.MapPath("~") + path;
                    if (!Directory.Exists(uploadpath))
                    {
                        Directory.CreateDirectory(uploadpath);
                    }

                    string savepath1 = uploadpath + saveName;

                    //图片压缩上传

                    bool isSuccess = ReduceImage(img, savepath1, 50);
                    if (isSuccess)
                    {
                        System.IO.File.Delete(savepath);
                        return Json(new { Success = true, FilePath = path + saveName, FileName = fileName, FileExt = ".jpg", Message = "上传成功!" });
                    }
                }
                return Json(new { Success = false, FilePath = "", FileName = "", FileExt = "", Message = "上传失败!" }); ;
            }

            catch (Exception ex)
            {
                return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

 

/// <summary>
        /// 压缩图片并保存
        /// </summary>
        /// <param name="iSource">图片文件</param>
        /// <param name="outPath">文件保存路径</param> 例如 var outPath = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(file.FileName));
        /// <param name="flag">值越大代表图片质量越好,一般默认控制在50为最佳压缩质量</param>
        /// <returns></returns>
        public static bool ReduceImage(Image iSource, string outPath, int flag)
        {
            ImageFormat tFormat = iSource.RawFormat;
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageDecoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                    iSource.Save(outPath, jpegICIinfo, ep);
                else
                    iSource.Save(outPath, tFormat);
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
            }
        }

 

posted @ 2018-07-25 11:20  wuther  阅读(3102)  评论(0编辑  收藏  举报