• dropzone实现拖放文件上传并预览图片


    下载引用Js

    1. 官网及演示地址: http://www.dropzonejs.com

    2. Github地址:https://github.com/enyo/dropzone

    3. 引用(使用官网样式,将 https://github.com/enyo/dropzone/tree/master/downloads 此目录文件,添加到项目):

    <link href="/Scripts/dropzone/css/dropzone.css" rel="stylesheet" />
    <script src="/Scripts/dropzone/dropzone.js"></script>

    JS代码

    Dropzone.options.myDropzone = {
        //指定处理上传图片的路径
        url: "/JKQMgr/UploadImages",
        //最大文件大小,单位是 MB
        maxFilesize: 5,
        //默认false。如果设为true,则会给文件添加上传取消和删除预览图片的链接
        addRemoveLinks: true,
        //指明允许上传的文件类型,格式是逗号分隔的 MIME type 或者扩展名。例如:image/*,application/pdf,.psd,.obj
        acceptedFiles: "image/*",
        //指明是否允许 Dropzone 一次提交多个文件。默认为false。如果设为true,则相当于 HTML 表单添加multiple属性。
        uploadMultiple: true,
        //关闭自动上传功能,默认会true会自动上传
        //也就是添加一张图片向服务器发送一次请求
        autoProcessQueue: false,
        //每次上传的最多文件数,经测试默认为2,
        //记得修改web.config 限制上传文件大小的节
        parallelUploads: 100,
        dictDefaultMessage: "拖拽图片或者点击",
        dictFileTooBig: "图片最大5M",
        dictInvalidFileType: "只能上传图片",
        dictRemoveFile: "移除",
        //一个函数,在 Dropzone 初始化的时候调用,可以用来添加自己的事件监听器。
        init: function () {
            var msg = "支持jpg、jpeg、png、gif格式,大小不超过5M.";
            var spanMsg = $("#spanMsg");
    
            var btUploadAll = $("#btUploadAll");
            var submitButton = document.querySelector("#btUploadAll")
            myDropzone = this; // closure
            //为上传按钮添加点击事件
            submitButton.addEventListener("click", function () {
                btUploadAll.attr("disabled", true);
                //手动上传所有图片
                myDropzone.processQueue();
            });
    
            //当添加图片后的事件,上传按钮恢复可用
            this.on("addedfile", function () {
                btUploadAll.removeAttr("disabled");
                spanMsg.text(msg);
            });
    
            //当上传完成后的事件,接受的数据为JSON格式
            this.on("complete", function (data) {
                if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
                    var res = eval('(' + data.xhr.responseText + ')');
                    if (res.Result) {
                        msg = "恭喜,已成功上传" + res.Count + "张照片!";
                        $("#Image").val(res.ImgNames);
                        spanMsg.attr("style", "color:green;")
                    } else {
                        msg = "上传失败,失败的原因是:" + res.Message;
                        spanMsg.attr("style", "color:red;")
                    }
                    spanMsg.text(msg);
                }
            });
    
            //删除图片的事件,当上传的图片为空时,使上传按钮不可用状态
            this.on("removedfile", function () {
                if (this.getAcceptedFiles().length === 0) {
                    btUploadAll.attr("disabled", true);
                    spanMsg.text(msg);
                }
            });
        }
    };

    C#后台代码

            /// <summary>
            /// 批量上传图片
            /// </summary>
            /// <returns></returns>
            [HttpPost]
            public JsonResult UploadImages()
            {
                bool isSavedSuccessfully = true;
                int count = 0;
                int code = 0;
                string msg = "";
                string result = "";
                string image_name = "";
    
                string fileName = "";
                string fileExtension = "";
                string filePath = "";
                string fileNewName = "";
                string uploadTypes = ".gif|.jpg|.jpeg|.png|.bmp";
                StringBuilder sbImgNames = new StringBuilder();
                try
                {
                    string directoryPath = HttpContext.Server.MapPath("/Upload/serviceimage/");
                    //目录如果不存在先创建
                    if (!Directory.Exists(directoryPath))
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    for (int i = 1; i <= Request.Files.Count; i++)
                    {
                        HttpPostedFileBase file = Request.Files[i - 1];
                        if (file != null && file.ContentLength > 0)
                        {
                            fileName = file.FileName;
                            //得到扩展名
                            fileExtension = Path.GetExtension(fileName);
                            //设置文件名(1#Guid.jpg   序号 + # + Guid + 扩展名
                            fileNewName = Guid.NewGuid().ToString() + fileExtension;
                            #region 服务器端校验
                            //大小
                            if (file.ContentLength > 5 * 1024 * 1024)
                            {
                                continue;
                            }
                            //扩展名 使用正则匹配
                            if (!Regex.IsMatch(fileExtension, uploadTypes, RegexOptions.IgnoreCase))
                            {
                                continue;
                            }
                            #endregion
                            //路径合并
                            filePath = Path.Combine(directoryPath, fileNewName);
                            //保存文件
                            file.SaveAs(filePath);
    
                            #region 使用HTTP方式上传到文件服务器同时生成缩略图
                            NameValueCollection postData = new NameValueCollection();
                            postData.Add("userid", base.ID);
                            result = WebHelper.HttpUploadFile(APIConfig.UploadServiceImage, filePath, "barimage", "text/html; charset=utf-8", postData);
                            JObject jObject = (JObject)JsonConvert.DeserializeObject(result);
                            code = (int)jObject["code"];
                            msg = (String)jObject["msg"];
                            if (code == 200)
                            {
                                image_name = (String)jObject["data"];
                                #region 拼接图片名称
                                //拼接图片名称
                                sbImgNames.Append(i.ToString());
                                sbImgNames.Append("#");
                                sbImgNames.Append(image_name);
                                if (i < Request.Files.Count)
                                {
                                    sbImgNames.Append(",");
                                }
                                #endregion
                            }
                            #endregion
    
                            //总数目 +1
                            count++;
                        }
                    }
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                    isSavedSuccessfully = false;
                }
    
                return Json(new
                {
                    Result = isSavedSuccessfully,
                    Count = count,
                    Message = msg,
                    ImgNames = sbImgNames.ToString()
                });
            }


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    函数宏实现循环左移
    函数宏判断小端
    Linux下32位与64位数据类型大小
    转:C语言嵌入式系统编程之软件架构篇
    转:详解大端小段模式
    time函数计算时间
    匈牙利命名法
    20131030
    20131029
    20131028
  • 原文地址:https://www.cnblogs.com/ful1021/p/4804352.html
Copyright © 2020-2023  润新知