aetherupload.js 多文件上传写法 v1.0
2020年12月28日
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 |
var AetherUpload = { upload: function () { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); this.locale; this.resourceDom = this.wrapperDom.find('#aetherupload-resource'); //上传按钮 this.outputDom = this.wrapperDom.find('#aetherupload-output'); //消息提示 this.progressBarDom = this.wrapperDom.find('#aetherupload-progressbar'); //进度条 this.resource = this.resourceDom[0].files[0]; this.resourceName = this.resource.name; this.resourceSize = this.resource.size; this.resourceTempBaseName = ''; this.resourceExt = ''; this.chunkSize = 0; this.chunkCount = 0; this.groupSubDir = ''; this.savedPath = ''; this.resourceHash = ''; this.blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice; this.i = 0; this.messages = this.getLocalizedMessages(); this.storageHost = $('#aetherupload-storage-host').length ? $('#aetherupload-storage-host').val() : ''; /** * 浏览器是否支持这个文件上传组件 */ if (!this.blobSlice) { this.outputDom.text(this.messages.error_unsupported_browser); return; } /** * 文件大小如果等于0保存 */ if (this.resourceSize === 0) { this.outputDom.text(this.messages.error_invalid_resource_size); return; } /** * 文件类型报错 */ if (this.resourceName.substring(this.resourceName.lastIndexOf('.') + 1, this.resourceName.length) === '') { this.outputDom.text(this.messages.error_invalid_resource_type); return; } this.outputDom.text(this.messages.status_upload_begin); //开始上传文字提示 this.resourceDom.attr('disabled', 'disabled'); if (!('FileReader' in window) || !('File' in window) || typeof SparkMD5 === 'undefined') { this.preprocess(); //浏览器不支持读取本地文件,跳过计算hash } else if (this.laxMode === true) { this.preprocess(); //宽松模式,跳过计算hash } else { this.calculateHash(); } }, /** * 计算hash */ calculateHash: function () { var _this = this; var clientChunkSize = 4000000; var chunks = Math.ceil(_this.resource.size / clientChunkSize); //看看能切成几份 var currentChunk = 0; //用于统计当前进行哪一步 var spark = new SparkMD5.ArrayBuffer(); //md5 var fileReader = new FileReader(); //对象允许Web应用程序异步读取存储在用户计算机上的文件 fileReader.onload = function (e) { spark.append(e.target.result); //数据添加到spark准备计算md5 ++currentChunk; _this.outputDom.text(_this.messages.status_hashing + ' ' + parseInt(currentChunk / chunks * 100) + '%'); //显示百分比 if (currentChunk < chunks) { loadNext(); } else { _this.resourceHash = spark.end(); //计算md5 _this.preprocess(); //调用预处理 } }; //绑定错误事件,如果文件上传出错进入预处理阶段 fileReader.onerror = function () { _this.preprocess(); //调用预处理 }; function loadNext() { var start = currentChunk * clientChunkSize; var end = start + clientChunkSize >= _this.resource.size ? _this.resource.size : start + clientChunkSize; fileReader.readAsArrayBuffer(_this.blobSlice.call(_this.resource, start, end)); } loadNext(); }, /** * 准备 */ preprocess: function () { //预处理 var _this = this; $.ajax({ url : _this.storageHost + _this.preprocessRoute, type : 'POST', dataType : 'json', xhrFields : { //跨域请求设置 withCredentials: true }, crossDomain: true, data: { resource_name: _this.resourceName, resource_size: _this.resourceSize, resource_hash: _this.resourceHash, //获取文件md5 locale : _this.locale, group : _this.group }, success: function (rst) { //返回错误信息 if (rst.error) { _this.outputDom.text(rst.error); return; } _this.resourceTempBaseName = rst.resourceTempBaseName; _this.resourceExt = rst.resourceExt; _this.chunkSize = rst.chunkSize; _this.chunkCount = Math.ceil(_this.resourceSize / _this.chunkSize); _this.groupSubDir = rst.groupSubDir; //急速秒传 if (rst.savedPath.length === 0) { _this.uploadChunk(); } else { _this.savedPath = rst.savedPath; if( _this.savedPathList.length){ //多文件执行这里 _this.savedPathList.prepend($('<input name="files[]" value="'+_this.savedPath+'">')) _this.resourceDom.removeAttr('disabled'); } else { _this.savedPathDom.val(_this.savedPath); _this.resourceDom.attr('disabled', 'disabled'); } _this.outputDom.text(_this.messages.status_upload_succeed); _this.progressBarDom.css('width', '100%'); typeof(_this.callback) !== 'undefined' ? _this.callback() : null; //上传成功的回调方法 } }, error: function (XMLHttpRequest, textStatus, errorThrown) { _this.outputDom.text(_this.messages.error_upload_fail); //返回上传失败错误信息 } }); }, /** * 上传和切割文件 */ uploadChunk: function () { var _this = this; var start = this.i * this.chunkSize; var end = Math.min(this.resourceSize, start + this.chunkSize); var form = new FormData(); //创建一个表单数据 form.append('resource_chunk' , this.resource.slice(start, end)); form.append('resource_ext' , this.resourceExt); form.append('chunk_total' , this.chunkCount); form.append('chunk_index' , this.i + 1); form.append('resource_temp_basename', this.resourceTempBaseName); form.append('group' , this.group); form.append('group_subdir' , this.groupSubDir); form.append('locale' , this.locale); form.append('resource_hash' , this.resourceHash); $.ajax({ url : _this.storageHost + _this.uploadingRoute, type : 'POST', data : form, dataType : 'json', xhrFields: { withCredentials: true }, cache : false, //关闭缓存 crossDomain : true, processData : false, contentType : false, success : function (rst) { if ((rst instanceof Object) !== true) { _this.outputDom.text(_this.messages.error_invalid_server_return); return; } if (rst.error === 'undefined' || rst.error) { _this.outputDom.text(rst.error); return; } var percent = parseInt((_this.i + 1) / _this.chunkCount * 100); _this.progressBarDom.css('width', percent + '%'); _this.outputDom.text(_this.messages.status_uploading + ' ' + percent + '%'); if (rst.savedPath !== 'undefined' && rst.savedPath !== '') { _this.savedPath = rst.savedPath; console.log(_this.savedPathList) if( _this.savedPathList.length){ //多文件执行这里 _this.savedPathList.prepend($('<input name="files[]" value="'+_this.savedPath+'">')) _this.resourceDom.removeAttr('disabled'); } else { _this.savedPathDom.val(_this.savedPath); _this.resourceDom.attr('disabled', 'disabled'); } _this.outputDom.text(_this.messages.status_upload_succeed); _this.progressBarDom.css('width', '100%'); typeof(_this.callback) !== 'undefined' ? _this.callback() : null; //上传成功的回调方法 } else { ++_this.i; _this.uploadChunk(); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (XMLHttpRequest.status === 0) { _this.outputDom.text(_this.messages.status_retrying); _this.sleep(5000); _this.uploadChunk(); } else { _this.outputDom.text(_this.messages.error_upload_fail); } } }); }, /** * 睡眠暂停方法 * @param milliSecond */ sleep: function (milliSecond) { var wakeUpTime = new Date().getTime() + milliSecond; while (true) { if (new Date().getTime() > wakeUpTime) { return; } } }, /** * 成功后回调方法 * @param callback * @returns {AetherUpload} */ success: function (callback) { this.callback = callback; return this; }, /** * 获取准备路由的方法 * @param route * @returns {AetherUpload} */ setPreprocessRoute: function (route) { this.preprocessRoute = route; return this; }, /** * 上传路由的方法 * @param route * @returns {AetherUpload} */ setUploadingRoute: function (route) { this.uploadingRoute = route; return this; }, /** * 设置组 * @param group * @returns {AetherUpload} */ setGroup: function (group) { this.group = group; return this; }, /** * 设置保存路径 * @param selector * @returns {AetherUpload} */ setSavedPathField: function (selector) { this.savedPathDom = $(selector); return this; }, /** * 设置多文件保存路径 * @param selector */ savedPathList: function (selector) { this.savedPathList = $(selector); return this; }, /** * 设置模式宽松模式 * @param isLax * @returns {AetherUpload} */ setLaxMode: function (isLax) { this.laxMode = isLax; return this; }, /** * 信息提示 * @returns {*} */ getLocalizedMessages: function () { var lang = navigator.language ? navigator.language : navigator.browserLanguage; var locales = Object.getOwnPropertyNames(this.text); for (var k in locales) { if (lang.indexOf(locales[k]) > -1) { this.locale = locales[k]; return this.text[this.locale]; } } this.locale = 'en'; return this.text[this.locale]; }, /** * 多语言转义表 */ text: { en: { status_upload_begin: 'upload begin', error_unsupported_browser: 'Error: unsupported browser', status_hashing: 'hashing', status_instant_completion_success: 'upload succeed (instant completion) ', status_uploading: 'uploading', status_upload_succeed: 'upload succeed', status_retrying: 'network problem, retrying...', error_upload_fail: 'Error: upload fail', error_invalid_server_return: 'Error: invalid server return value', error_invalid_resource_size: 'Error: invalid resource size', error_invalid_resource_type: 'Error: invalid resource type' }, zh: { status_upload_begin: '开始上传', error_unsupported_browser: '错误:上传组件不被此浏览器支持', status_hashing: '正在哈希', status_instant_completion_success: '上传成功(秒传)', status_uploading: '正在上传', status_upload_succeed: '上传成功', status_retrying: '网络故障,正在重试……', error_upload_fail: '错误:上传失败', error_invalid_server_return: '错误:无效的服务器返回值', error_invalid_resource_size: '错误:无效的文件大小', error_invalid_resource_type: '错误:无效的文件类型' } } }; /* * 创建AetherUpload对象的全局方法 * resource 文件对象 * group 分组名 */ function aetherupload(resource) { var newInstance = Object.create(AetherUpload); newInstance.wrapperDom = $(resource).parents('.aetherupload-wrapper'); newInstance.group = 'file'; //分组的默认值 newInstance.savedPathDom = newInstance.wrapperDom.find('#aetherupload-savedpath'); //单文件资源储存地址所在节点的默认值 newInstance.savedPathList = newInstance.wrapperDom.find('#aetherupload-savedpath-list'); //多文件资源储存地址所在节点的默认值 newInstance.preprocessRoute = '/aetherupload/preprocess'; //预处理路由的默认值 newInstance.uploadingRoute = '/aetherupload/uploading'; //上传路由的默认值 newInstance.laxMode = false; //宽松模式 return newInstance; } |