WebUploader of the front part uploading large files

WebUploader of a single large file upload slice (distal implemented)

1, components Introduction

webuploader (official definition): It is a mainly to HTML5, Flash, supplemented by the file upload component, by way of a large file fragmentation / concurrent uploads, which greatly improves the efficiency of uploaded files, while compatible with multiple browser versions;

Links: WebUploader official website .

2, the front end code to achieve

First, download the components and introduced to the project file;

import WebUploader from "webuploader";

WebUploader Package

Background simulation parameters required for the present example:

parameter Explanation
guid File fragmentation GUID
md5Value MD5 value of file
chunk The current slice number of the current file transfer
chunks The current fragmentation of the total number of file transfer
id ID documents
fileName file name
file document content

Man of few words said, directly on the code.

//引入组件
import WebUploader from "webuploader";
let uploader = null,GUID = null;

onReady(){		
		GUID = WebUploader.Base.guid();//每个文件有自己唯一的guid
        uploader = WebUploader.create({
           //设置选完文件后是否自动上传
           auto: false,
           //swf文件路径
           // swf: 'vendor/webUpload/Uploader.swf',
           // 文件接收服务端。
           server: "http://www.baidu.com/BigFileUpload", //服务器端的上传页面地址
           // 选择文件的按钮。可选。
           // 内部根据当前运行是创建,可能是input元素,也可能是flash.
           pick: "#fileupload",//点击选择文件的按钮id
           chunked: true, //开启分块上传
           chunkSize: 10 * 1024 * 1024,//10M 一个分片
           chunkRetry: 3, //网络问题上传失败后重试次数
           threads: 1, //上传并发数
           //fileNumLimit :1,
           fileSizeLimit: 1000 * 1024 * 1024, //最大1GB
           fileSingleSizeLimit: 1000 * 1024 * 1024,
           resize: false,//不压缩
           formData: {},
           //选择文件类型
           accept: {
               title: 'Zip files',
               extensions: 'zip',
               mimeTypes: '.zip'
           },
       });

       // 当有文件被添加进队列的时候
       uploader.on("fileQueued", function (file) {
       		//进行是否采用分片上传判断
			if(file.size > 50*1024*1024){
				uploader.option.chunked = true;
			}else{ //文件的大小 小于 50M 则不采用分片上传
				uploader.option.chunked = false;
			}
       
			//md5计算
              uploader
                  .md5File(file)
                  .progress(function (percentage) {
                      // console.log("Percentage:", percentage);
                  })
                  // MD5计算完毕,可以点击上传了
                  .then(function (fileMd5) {
                      // 完成
                      file.wholeMd5 = fileMd5; //获取到了md5
                  });
       });

       // 文件上传过程中创建进度条实时显示。
       uploader.on("uploadProgress", function (file, percentage) {                
           if (percentage * 100 > 100) {
               return;
           }
           dialogUploadVm.progress = parseInt(percentage * 100);
       });
		
		// 当validate不通过时,会以派送错误事件的形式通知调用者。
       uploader.on("error", function (type) {                
           if (type == 'Q_EXCEED_SIZE_LIMIT') {
               notification.error({
                   message: '上传的文件大小不能超过1GB',
                   title: '通知'
               });
           }else if(type == 'Q_TYPE_DENIED') {//当文件类型不满足时触发
               notification.error({
                   message: '仅支持上传zip压缩文件',
                   title: '通知'
               });
           }
       });

       //发送前填充数据,主要用来询问是否要添加附带参数
       uploader.on("uploadBeforeSend", function (block, data) {
           // block为分块数据。
           console.log(block);
           console.log(data);                
           
           // file为分块对应的file对象。
           var file = block.file;
           var fileMd5 = file.wholeMd5;

           // 修改data可以控制发送哪些携带数据。
           // 将存在file对象中的md5数据携带发送过去。

           data.chunk = block.chunk;
           data.chunks = block.chunks;
           data.md5Value = fileMd5; //md5,文件的MD5值 
           data.id = file.id;//文件ID
           data.fileName = file.name;//文件名称
           // data.file = file;//当前所传分片
           data.guid = GUID;
           data.type = 0;

           // 删除其他数据(默认的上传字段)
           delete data.lastModifiedDate;
           delete data.size;
           delete data.name;           
       });

		//当文件上传成功时触发。
       uploader.on("uploadSuccess", function (file, response) {
       		//response {Object}服务端返回的数据
           if (response.code == 1602) {
               notification.error({
                   message: '上传失败,已存在最新版本的文件',
                   title: '通知'
               });
           } else if (response.code == 0) {
				//success
           } else {
               notification.warn({
                   message: response.msg,
                   title: '通知'
               });
               setTimeout(() => {
                   dialogUploadVm.progress = 0;
               }, 1500);
           }
       });
       
       //当文件上传出错时触发。
       uploader.on("uploadError", function (file, reason) {
       		//reason {String}出错的code
           notification.error({
               message: "上传出错,请重新上传",
               title: '通知'
           });
       });

		//上传完成后回调
       uploader.on("uploadComplete", function (file) {           
           uploader.reset();//重置uploader。目前只重置了队列。
       });

		//上传完后的回调方法
       uploader.on("uploadFinished", function () {           
           //提交表单
           uploader.reset();//重置uploader。目前只重置了队列。
       });
}      

//确定上传的时候执行此函数:
function okButton(){
	//假设拿到了需要额外上传的内容,比如 版本号,版本信息
	let inputJson = {
        "version": "",
        "updateInfo": "",
    };
    
	uploader.options.formData = {//这里可以设置组件外需要上传的参数
	     "type": 0,//与组件内部type参数冲突,若要使用需在 uploadBeforeSend 时修改 data.type;
	     "version": this.inputJson.version,
	     "changeLog": this.inputJson.updateInfo,
	};
	uploader.upload(); //上传
}

3, Notes

  1. The condition is determined whether to adopt part uploading functional code is written on the "file is added into the queue time", i.e. fileQueued ; if "uploadBeforeSend" will be judged invalid.
  2. In uploadBeforeSend performed parameter assignment-related components, the components do not need to bring their own default parameters delete delete .
  3. Set parameters need to upload the outer component, with uploader.options.formData assignment.
  4. May not be able to select the file select the file again, you need to uploader.reset (); reset it queue.

4, where parameter passing

Parameter passing shots

5, is currently experiencing a pit

  • Click the button does not appear bomb box
    simulation official document upload button, click on it to find out how no response, but when you press F12 when you can click on. WebUploader initialization of fact, a package input tag, the attribute type = 'file'. The size of the initialization time because not obtain the correct size or the container itself, this time initialization out of this transparent layer 1px 1px * , less than a fundamental point, will not trigger a click event, only need to add some inside the css Code:
    Button html screenshots
#fileupload div:nth-child(2){
    width:100%!important;
    height:100%!important;
}
Published an original article · won praise 4 · views 41

Guess you like

Origin blog.csdn.net/wealth_nana/article/details/105051649