Native js file upload and download packages

 

First, download

1, Code

const fileDownloadClick = (obj) => {// compatible solution
  if( document.all ){
    obj.click();
  } else {
    let event = document.createEvent("MouseEvents");
    event.initEvent('click', true, true);
    obj.dispatchEvent(event);
  }
}
const fileDownload = (res, obj) => {// downloads
    /*
    obj :{
      Download userName people
      weeklyTime download time
      weeklyType Download Type 
    }
  */ 
  let blob = new Blob([res]);
  let url = window.URL.createObjectURL(blob);
  let link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;
  link.setAttribute('download', `${obj.userName || ' '}_${obj.weeklyTime || dateFormatYMD(new Date())}_${obj.weeklyType || '.xlsx' }`);
  document.body.appendChild(link);
  // link.click();
  fileDownloadClick(link);
  window.URL.revokeObjectURL(url);
}

2, when the request for an increase in the request header

responseType: 'blob',

3, using

res: Background returned file stream (garbled something similar) 
obj: Download file name

// page calls
this.fileDownload = (res, obj)

 

Second, upload (based vue)

1, page uses 

<input type="file" ref="upload" @change='handleUploadChange($event)' style="display:none;">

  handleUploadFile (row) {// triggered by an event 
    this.$refs['upload'].click();
  },
 
 
   async handleUploadChange(e){ // 
      try{
        let res = await this.CommonUpload(e);
        if (res.code == '200') {// get additional code value according to a given background
            this.handleProjectAddFile(res.data)
        }else{}
      }
    catch(err){}
  }

 

2, the method of the package (only determine the size, may also be determined by other types accept to receive type, etc.)

CommonUpload(e){ 
        const files = e.target.files;
        formdat to let formdat = new ();
        if(files && files[0]) {
            const file = files[0];
            if(file.size > 1024 * 1024 *3) {
                alert ( 'file size can not exceed 3M');
                return;
            } else {
                formData.append("multipartFile", file); 
            }
        }
        this.uploadFile_ (formData) // interface method to upload call
    }

 

3, the same problem when selecting the file again, failure

Solution: (execute the following after uploading) 
the this $ refs [ 'the Upload'] value = ''; // to solve the problem input file the second time failed.

The reason:
File value is the new value of the selected input, so the next time choose the same file, it does not trigger a change event

Guess you like

Origin www.cnblogs.com/-roc/p/12151647.html