JQuery上传文件(客户端)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JQuery上传文件(客户端)相关的知识,希望对你有一定的参考价值。

  现在工作中使用的文件上传插件是以前的同事使用Flash实现的,最近经常接到客户的反馈说上传插件不能使用,经调查发现是部份客户的浏览器阻止了Flash的运行,需要手动开启Flash才能正常使用,客户体验非常糟糕,毕竟不可能要求每个客户都知道怎么去开启浏览器支持Flash。

  思量过后决定把Flash上传修改为JQuery上传。

  上代码:

技术分享
  1 ; (function ($, window, document, undefined) {
  2     var fileExtentionAcceptConfig = [
  3         { extention: ".3gpp", accept: "audio/3gpp" },
  4         { extention: ".3gpp", accept: "video/3gpp" },
  5         { extention: ".ac3", accept: "audio/ac3" },
  6         { extention: ".asf", accept: "allpication/vnd.ms-asf" },
  7         { extention: ".au", accept: "audio/basic" },
  8         { extention: ".bmp", accept: "image/bmp" },
  9         { extention: ".css", accept: "text/css" },
 10         { extention: ".csv", accept: "text/csv" },
 11         { extention: ".doc", accept: "application/msword" },
 12         { extention: ".dot", accept: "application/msword" },
 13         { extention: ".dtd", accept: "application/xml-dtd" },
 14         { extention: ".dwg", accept: "image/vnd.dwg" },
 15         { extention: ".dxf", accept: "image/vnd.dxf" },
 16         { extention: ".gif", accept: "image/gif" },
 17         { extention: ".htm", accept: "text/html" },
 18         { extention: ".html", accept: "text/html" },
 19         { extention: ".jp2", accept: "image/jp2" },
 20         { extention: ".jpe", accept: "image/jpeg" },
 21         { extention: ".jpeg", accept: "image/jpeg" },
 22         { extention: ".jpg", accept: "image/jpeg" },
 23         { extention: ".js", accept: "text/javascript" },
 24         { extention: ".js", accept: "application/javascript" },
 25         { extention: ".json", accept: "application/json" },
 26         { extention: ".mp2", accept: "audio/mpeg" },
 27         { extention: ".mp2", accept: "video/mpeg" },
 28         { extention: ".mp3", accept: "audio/mpeg" },
 29         { extention: ".mp4", accept: "audio/mp4" },
 30         { extention: ".mp4", accept: "video/mp4" },
 31         { extention: ".mpeg", accept: "video/mpeg" },
 32         { extention: ".mpg", accept: "video/mpeg" },
 33         { extention: ".mpp", accept: "application/vnd.ms-project" },
 34         { extention: ".ogg", accept: "application/ogg" },
 35         { extention: ".ogg", accept: "audio/ogg" },
 36         { extention: ".pdf", accept: "application/pdf" },
 37         { extention: ".png", accept: "image/png" },
 38         { extention: ".pot", accept: "application/vnd.ms-powerpoint" },
 39         { extention: ".pps", accept: "application/vnd.ms-powerpoint" },
 40         { extention: ".ppt", accept: "application/vnd.ms-powerpoint" },
 41         { extention: ".rtf", accept: "application/rtf" },
 42         { extention: ".rtf", accept: "text/rtf" },
 43         { extention: ".svf", accept: "image/vnd.svf" },
 44         { extention: ".tif", accept: "image/tiff" },
 45         { extention: ".tiff", accept: "image/tiff" },
 46         { extention: ".txt", accept: "text/plain" },
 47         { extention: ".wdb", accept: "application/vnd.ms-works" },
 48         { extention: ".wps", accept: "application/vnd.ms-works" },
 49         { extention: ".xhtml", accept: "application/xhtml+xml" },
 50         { extention: ".xlc", accept: "application/vnd.ms-excel" },
 51         { extention: ".xlm", accept: "application/vnd.ms-excel" },
 52         { extention: ".xls", accept: "application/vnd.ms-excel" },
 53         { extention: ".xlt", accept: "application/vnd.ms-excel" },
 54         { extention: ".xlw", accept: "application/vnd.ms-excel" },
 55         { extention: ".xml", accept: "text/xml" },
 56         { extention: ".xml", accept: "application/xml" },
 57         { extention: ".zip", accept: "aplication/zip" },
 58         { extention: ".xlsx", accept: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }
 59     ];
 60 
 61     var fileTypeConfig = [
 62         { id: 1, name: "商品图片", code: "product" },
 63         { id: 2, name: "PC端装修图片", code: "template" },
 64         { id: 3, name: "其它图片", code: "other" },
 65         { id: 4, name: "手机端装修图片", code: "H5Decorating" },
 66         { id: 5, name: "手机端装修图片", code: "APPDecorating" },
 67         { id: 6, name: "订单相关图片(退货、换货)", code: "Order" },
 68         { id: 7, name: "会员营业执照", code: "UserBusinessLicense" },
 69         { id: 8, name: "会员身份证", code: "UserIDCard" },
 70         { id: 9, name: "试装会员", code: "TrailUser" },
 71         { id: 10, name: "建议反馈", code: "Suggest" },
 72     ];
 73 
 74     var jqueryUpload = function (ele, opt) {
 75         var $this = this;
 76 
 77         $this.$element = $(ele);
 78         $this._default = {
 79             uploadUrl: "/controls/Upload.ashx",
 80             buttonStyle: {
 81                 "display": "inline-block",
 82                 "background-color": "#EC7B65",
 83                 "color": "white",
 84                 "padding": "4px 10px",
 85                 "border-radius": "2px",
 86                 "cursor": "pointer",
 87                 "font-size": "12px",
 88                 "line-height": "18px"
 89             },
 90             offerId: null,//客户ID
 91             uploadFolderId: null,//文件夹ID
 92             uploadFolderName: null,//文件夹名称,上传路径=‘uploads/类型code/uploadName‘
 93             fileType: null,//文件类型1|2|3...
 94             noThumb: true,//不生成缩略图
 95             waterMark: null,//是否生成水印
 96             fileCount: 1,
 97             maxSize: 1024,//图片最大尺寸,单位KB;默认1M=1024*1024
 98             allowFileType: null,//支持的文件类型,可为后缀名数组:[‘.jpg‘, ‘.png‘...],也可以是字符串表式一类文件:‘image‘|‘audio‘...
 99             onError: null,
100             onSelected: null,
101             onProcess: null,
102             onUploaded: null
103         };
104         $this.option = $.extend({}, $this._default, opt);
105         if ($$.isString($this.option.allowFileType)) {
106             $this.option.allowFileType = $$.sae(fileExtentionAcceptConfig)
107                 .findAll(function (x) { return $$.soe(x.accept).startWith($this.option.allowFileType); })
108                 .select(function (x) { return x.extention; })
109                 .toArray();
110         }
111 
112         $this.controlId = $this.generateId();
113         $this.initControl();
114     }
115 
116     jqueryUpload.prototype = {
117         resetOption: function (option) {
118             var $this = this;
119 
120             $this.option = $.extend($this.option, option);
121             $this.initControl();
122         },
123         initControl: function () {
124             var $this = this;
125 
126             var html = "127 <div id=‘ju-" + $this.controlId + "‘ class=‘ju-container‘>";
128             $this.$filecontrolHtml = "129     <input type=‘file‘";
130             if ($$.isArray($this.option.allowFileType)) {
131                 var accepts = $$.sae(fileExtentionAcceptConfig)
132                     .findAll(function (x) { return $$.tae($this.option.allowFileType).any(function (y) { return $$.compare(x.extention, y, true) == 0 }); })
133                     .select(function (x) { return x.accept; })
134                     .distinct()
135                     .toArray();
136                 $this.$filecontrolHtml += " accept=‘" + accepts.join(‘,‘) + "‘";
137             }
138             $this.$filecontrolHtml += " style=‘display:none;‘ />";
139             html += "140     <span class=‘ju-upload‘>上传</span>141 </div>";
142             $this.$element.html(html);
143 
144             $this.$container = $this.$element.find(".ju-container");
145             $this.resetInputControl();
146             $this.$uploadbutton = $this.$container.find(".ju-upload");
147             if ($$.isObject($this.option.buttonStyle)) {
148                 $this.$uploadbutton.css($this.option.buttonStyle);
149                 $this.$uploadbutton.hover(function () {
150                     $this.$uploadbutton.css({
151                         "background-color": "#EF8E7C"
152                     });
153                 }, function () {
154                     $this.$uploadbutton.css({
155                         "background-color": "#EC7B65"
156                     });
157                 });
158             } else {
159                 $this.$uploadbutton.addClass($this.option.buttonStyle);
160             }
161 
162             $this.$uploadbutton.click(function () {
163                 $this.$filecontrol.click();
164             });
165         },
166         resetInputControl: function () {
167             var $this = this;
168 
169             if (!$$.isNullOrUndefined($this.$filecontrol)) {
170                 $this.$filecontrol.remove();
171             }
172 
173             $this.$container.append($this.$filecontrolHtml);
174             $this.$filecontrol = $this.$container.find("input[type=‘file‘]");
175             $this.$filecontrol.change(function () {
176                 $this.fileSelected();
177             });
178         },
179         fileSelected: function () {
180             var $this = this;
181 
182             var file = $this.$filecontrol[0].files[0];
183 
184             if ($$.isArray($this.option.allowFileType)) {
185                 var fileExtention = $$.getFileExtention(file.name);
186                 if (!$$.sae($this.option.allowFileType).any(function (x) { return $$.compare(x, fileExtention, true) == 0; })) {
187                     $this.error("不支持的文件类型!");
188                     return;
189                 }
190             }
191 
192             if (file.size > $this.option.maxSize * 1024) {
193                 $this.error("文件大小不得超过" + ($this.option.maxSize >= 1024 ? $$.soe($this.option.maxSize / 1024).round(2, $$.enum.roundType.floor) + "MB" : $this.option.maxSize + "KB"));
194                 return;
195             }
196 
197             if ($$.isFunction($this.option.onSelected)) {
198                 var reader = new FileReader();
199                 reader.onload = function (e) {
200                     var $img = $("<img />");
201                     //$img.attr("src", e.target.result);
202                     //$img.attr("data-url", window.URL.createObjectURL(file));
203                     var imageUrl = window.URL.createObjectURL(file);
204                     $img.attr("src", imageUrl).css("cursor", "pointer");
205                     $this.option.onSelected($img);
206                     $img.click(function () {
207                         window.open(imageUrl);
208                     });
209                 }
210                 reader.readAsDataURL(file);
211             }
212             
213             $this.upload(file);
214         },
215         error: function (msg) {
216             var $this = this;
217 
218             if ($$.isFunction($this.option.onError)) {
219                 $this.option.onError(msg);
220             }
221 
222             $this.resetInputControl();
223         },
224         process: function (evt) {
225             var $this = this;
226             
227             if ($$.isFunction($this.option.onProcess)) {
228                 $this.option.onProcess(evt.total, evt.loaded);
229             }
230         },
231         upload: function (file) {
232             var $this = this;
233 
234             var formData = new FormData();
235             formData.append("file", file);
236             $.xtcShowLoading("上传中。。。");
237             try {
238                 var params = [];
239                 if (!$$.isNullOrUndefined($this.option.offerId)) {
240                     params.push("offerid=" + $this.option.offerId);
241                     if ($$.soe($this.option.offerId).toInt() > 0) {
242                         params.push("isoffer=1");
243                     }
244                 }
245                 if (!$$.isNullOrUndefined($this.option.uploadFolderId)) {
246                     params.push("cid=" + $this.option.uploadFolderId);
247                 }
248                 var uploadDir = "uploads";
249                 var fileType = null;
250                 if (!$$.isNullOrUndefined($this.option.fileType)) {
251                     var fileTypeId = $$.soe($this.option.fileType).toInt();
252                     params.push("type=" + fileTypeId);
253                     var fileType = $$.sae(fileTypeConfig)
254                         .firstOrDefault(function (x) { return x.id == fileTypeId; });
255                 }
256                 if (fileType != null) {
257                     uploadDir += "/" + fileType.code;
258                 } else {
259                     uploadDir += "/unknown";
260                 }
261                 if (!$$.isNullOrWhiteSpace($this.option.uploadFolderName)) {
262                     uploadDir += "/" + $this.option.uploadFolderName;
263                 }
264                 params.push("upload_dir=" + uploadDir);
265                 if (!$$.isNullOrUndefined($this.option.noThumb)) {
266                     params.push("no_thumb=" + ($this.option.noThumb ? 1 : 0));
267                 }
268                 if (!$$.isNullOrUndefined($this.option.waterMark)) {
269                     params.push("WaterMark=" + ($this.option.waterMark ? 1 : 0));
270                 }
271                 $.ajax({
272                     url: $this.option.uploadUrl + "?" + params.join(‘&‘),
273                     type: "POST",
274                     data: formData,
275                     contentType: false,
276                     processData: false,
277                     dataType: "html",
278                     xhr: function () {
279                         var xhr = $.ajaxSettings.xhr();
280                         xhr.upload.addEventListener("progress", function (evt) { $this.process(evt); }, false);
281                         return xhr;
282                     }
283                 }).done(function (data) {
284                     if ($$.isNullOrUndefined(data)) {
285                         $this.error("上传失败,未知错误!");
286                     } else if (data.indexOf(".") <= 0) {
287                         $this.error(data);
288                     } else if ($$.isFunction($this.option.onUploaded)) {
289                         $this.option.onUploaded(data)
290                         $this.resetInputControl();
291                     }
292                 }).fail(function (err) {
293                     if (typeof (err) == "object" && err.constructor == Object && err.responseText) {
294                         $this.error(err.responseText);
295                     } else {
296                         $this.error(err);
297                     }
298                 }).always(function () {
299                     $.xtcHideLoading();
300                 });
301             }
302             catch (err) {
303                 $.xtcHideLoading();
304             }
305         },
306         generateId: function () {
307             var guid = "";
308             for (var i = 1; i <= 32; i++) {
309                 var n = Math.floor(Math.random() * 16.0).toString(16);
310                 guid += n;
311                 if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
312                     guid += "-";
313             }
314             return guid;
315         }
316     }
317 
318     $.fn.xtcUpload = function (option) {
319         return new jqueryUpload(this, option);
320     }
321 })(jQuery, window, document);
View Code

  如何使用?

<script type="text/javascript" src="/common_script/jsExtension.js?t=201708231435"></script><!--使用了上一篇随笔里编写的JS扩展插件,需要引入-->
<script type="text/javascript" src="/common_script/jqueryUpload.js"></script>
<script type="text/javascript">
    $(function () {
        var uploadControl = $(".uploadTest").xtcUpload({
            buttonStyle: "upload-button",//按钮样式,可以是一个css键值对实体,也可以是一个class名称
            uploadFolderId: 220,//上传文件夹ID
            uploadFolderName: ‘10月20日活动页‘,//上传文件夹名称
            fileType: 3,//文件类型,对应于JS文件中的fileTypeConfig
            maxSize: 500,//文件大小限制单位KB
            allowFileType: [".png", ".jpg"],//支持的文件类型,可为后缀名数组:[‘.jpg‘, ‘.png‘...],也可以是字符串表式一类文件:‘image‘|‘audio‘...
            //发生错误时调用的函数
            onError: function (msg) {
                Ecshop.Tool.Hint.Error({ info: msg });
            },
            //上传时进度条触发事件
            onProcess: function (total, loaded) {
                //百分比 loaded / total * 100
            },
            //上传完成时触发事件
            onUploaded: function (file) {
                $(".img-before-upload").append("<img src=‘/" + file + "‘ />");
            }
        });
        //当需要时(如上传文件夹变更)重置上传控件参数
        uploadControl.resetOption({
            uploadFolderId: 221
        });
    });
</script>
<div class="uploadTest"></div>
<div class="img-before-upload"></div>

 

以上是关于JQuery上传文件(客户端)的主要内容,如果未能解决你的问题,请参考以下文章

上传/下载之前/之后的客户端(javascript/jQuery)文件操作

JQuery Ajax从客户端上传文件和其他值[重复]

前端开发:功能强大的jQuery文件上传插件(jQuery File Upload)

如何使用简单的 jquery-ajax 调用上传文件

JQuery-File-Upload BlueImp文件上传EXIF方向旋转

Alamofire 文件上传出现错误“JSON 文本未以数组或对象开头,并且允许未设置片段的选项”