background

Due to the business relationship of our company, we need to implement the video uploading function compatible with IE8+ and support multiple breakpoint uploading. Therefore, the webuploader file upload plug-in developed by Baidu WebFE(FEX) team is used to achieve this business function.

General steps for uploading files

1. Js authentication (mainly to determine whether the video already exists, if so, return the uploaded file size of the video, only need to determine once) :

  • Step 1: Calculate MD5 for the video file. The larger the video file is, the longer it takes to calculate MD5

  • Step 2: Get the total size of the video file

  • Step 3: Transfer the video name, total file size, and MD5 string of the video file to tokenUrl

2. Return json parameters:

  • Success: Indicates whether the verification is successful

  • FileMd5: md5 of video files

  • Start: The size of the uploaded file (0 is returned if the file has not been uploaded, and the size of the uploaded file is returned if the file has been uploaded, for example, 30000 bytes, 20000 bytes is returned if the file has been uploaded)

3. After the verification is passed, the JS side will upload (the larger the video file, the more times it will be divided).

  • Step 1: Set the size of each segmented video stream according to the total size of the video file
  • Step 2: Add the MD5 string of the video file,
  • The size value of the uploaded video start (the first time is filled in according to the authentication of the JS end, the second time is filled in according to the last return), and the segmented video stream is transmitted to the upUrl
  • Return json as an argument:
  • Success: Verify whether the video stream is uploaded successfully
  • Start: indicates the uploaded size

Plug-in configuration resolution

HTML part

First, prepare the DOM structure, including the container for storing file information, select button and upload button.

<! -- Video list display -->
<ul class="resources_body_modal_add_list">
{#list queuedList as item}
<li class="resources_body_modal_add_list_item">
  <div class="resources_body_modal_add_list_item_hd" style="background-image: url({item.gvdPic})"></div> 
  <div class="resources_body_modal_add_list_item_bd">
    <input type="text" name="" placeholder="Here is the name of the video, click to modify it." class="form-control" value={item.name} on-blur={this.updateName(item_index, $event)} / >
  </div>
  <span class="resources_body_modal_add_list_item_icon" on-click={this.deleteQueuedFile(item_index)}>x</span> 
  <div class="resources_body_modal_add_list_item_bar">
    <div class="resources_body_modal_add_list_item_bar_progress"></div>
  </div>
</li> 
{/list}
</ul>
<! -- File upload button -->
<div class="resources_body_modal_add_field">
<div class="resources_body_modal_add_field_cell">
    <! -- Id used for configuration -->
  <div id="filePicker" class="resources_body_modal_add_field_cell_icon" r-hide={queuedList.length= =queuedLimit}>+</div>
  <p class="g-mb20" r-hide={queuedList.length= =queuedLimit}>Click upload video</p>
  <p r-hide={queuedList.length} class="js-empty">A maximum of {queuedLimit} videos can be uploaded at a time. A single video cannot exceed 4 GB</p>
  <p r-hide={! queuedList.length} class="js-full">Has chosen<span class="js-uploadLength"></span>A,<span class="js-uploadLeft"></span>
  </p>
</div> 
</div> 
Copy the code

Initialize webuploader

uploader = WebUploader.create({
    resize: false.// do not compress the image
    swf: base_URL + 'jslib/WebUploader/Uploader.swf'.// SWF file path
    method: "post".sendAsBinary : true.// File upload binary stream
    fileNumLimit: 10.// Verify the total number of files, exceeding which will not be allowed to join the queue
    fileSingleSizeLimit: 4*1024*1024*1024.// Verify that the size of a single file exceeds the limit
    server: upload_URL,// File receiving server
    pick: {
        id: '#filePicker'.// This id is the id of the outer div where you want to click on the upload file button
        multiple : true // Whether the file can be uploaded in batches, true can select multiple files at the same time
    },    
    chunked: true.// Whether to fragment large file uploads
    threads: true.// Number of concurrent uploads
    chunkSize:3*1024*1024.// Upload fragments. Each fragment is 2M. The default value is 5M
    prepareNextFile: true.// Preprocess the next shard while uploading the current shard
    //auto: false // Indicates whether the file is automatically uploaded
    chunkRetry : 1.// The number of times that automatic retransmission is allowed if a fragment fails due to network problems
    duplicate: false.// Repeat the selection
    // runtimeOrder: 'html5, flash'
    accept: {
        extensions: 'avi,wmv,rm,rmvb,mov,mkv,flv,mp4,f4v,3gp,ts,wma,wav,aac'.mimeTypes: '.avi,.wmv,.rm,.rmvb,.mov,.mkv,.flv,.mp4,.f4v,.3gp,.ts,.wma,.wav,.aac'
    }// Video file suffix
});

Copy the code

Listen for three points in time during the block upload process

WebUploader.Uploader.register({
    "before-send-file":"beforeSendFile"."before-send":"beforeSend"."after-send-file":"afterSendFile"}, {// Time point 1: call this function before all blocks are uploaded
    beforeSendFile:function(file){
        var deferred = WebUploader.Deferred();  
        //1, calculate file unique flag, used for breakpoint continuation
        (new WebUploader.Uploader()).md5File(file,0.2*1024*1024)  
            .progress(function(percentage){  
            })  
            .then(function(val){  
                fileMd5=val;  
                // Go to the next step after obtaining the file information
                deferred.resolve();  
            });  
        return deferred.promise();  
    },  
    // Point 2: If there are block uploads, this function is called before each block upload
    beforeSend:function(block){
        var deferred = WebUploader.Deferred();
        if(videoAdd[block.file.id] > block.start){
            // Block exists, skip
            deferred.reject();    
        }else{    
            // The block does not exist or is incomplete. Resend the block
            this.owner.options.formData={
              start: block.start,// Set the start point for uploading videos
              fileMd5: videoMd5[block.file.id]// Set MD5 as the unique identifier for video uploading
            }

            deferred.resolve();    
        } 
        return deferred.promise();  
    },  
    // Point 3: This function is called when all blocks have been successfully uploaded
    afterSendFile:function(file, response){
        // The block upload is successful, and the callback is successfulsuccessHandler(file, response, fileArr); }});Copy the code

Display user selection

Listen for the fileQueued event

uploader.on( 'fileQueued'.function( file ) {
    // Only videos that meet the criteria, including size, suffix, and number limit, will be added to the queue
    // Set the file loading state
    uploader.md5File(file)
    // Display progress in time
        .progress(function(percentage) {
            // The progress of obtaining file information is displayed according to percentage
        })
        / / finish
        .then(function(md5Val){
        // Start uploading})})Copy the code

The file upload progress is displayed

// Displays the file upload progress
uploader.on( 'uploadProgress'.function(file, percentage) {
  var $uploading= $('.js-uploading-'+file.id);
  var progressWid= (percentage*100) +The '%';
  $uploading.find('.js-bar').width(progressWid);
});
Copy the code

Failed to upload files. Procedure

// Failed to upload the file
uploader.on( 'uploadError'.function(file, reason) {$('.js-uploading-'+file.id).addClass('hidden');
  uploader.cancelFile(file);// Clear the queue placeholder
});
Copy the code

Select file error handling

uploader.on('error', errorHandler);
Copy the code

So far video upload function, basically can achieve.

tips:

  • When the upload button function is displayed in the pop-up window, attention should be paid to the initialization time and the destruction of the Webuploader instance, which should be processed after modal display and after hidden callback.
  • When you upload multiple files, you need to match the parameters for uploading blocks
  • The popover file selection button in IE8 may cause flash error. Just adjust the style when the popover is fully displayed