SoFunction
Updated on 2025-03-02

Native js implements file upload, download, encapsulation and other example methods

1. Download

1. Code

const fileDownloadClick = (obj) => { // Solve compatibility if(  ){
  ();
 } else {
  let event = ("MouseEvents");
  ('click', true, true);
  (event);
 }
}
const fileDownload = (res,obj) => { // download  /*
   obj :{
    userName downloader
    weeklyTime Download Time
    weeklyType Download Type
   }
  */ 
 let blob = new Blob([res]);
 let url = (blob);
 let link = ('a');
  = 'none';
  = url;
 ('download', `${ || ' '}_${ || dateFormatYMD(new Date())}_${ || '.xlsx' }`);
 (link);
 // ();
 fileDownloadClick(link);
 (url);
}

2. When requesting, add the request header

responseType: 'blob',

3. Use

res: File stream returned in the background( Something similar to garbled code )
obj:Download file name

//Called on the page = (res,obj)

2. Upload (based on vue)

1. Page usage

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



 handleUploadFile(row){ // Triggered by a certain event  this.$refs['upload'].click();
 },
 
 

  async handleUploadChange(e){ // 
   try{
    let res = await (e);
    if( == '200'){ // Get other code values, determine according to the background      ()
    }else{}
   }
catch(err){}
}

2. Method encapsulation (only determine the size, you can also determine the type to be received through accept, etc.)

CommonUpload(e){ 
    const files = ;
    let formData = new FormData();
    if(files && files[0]) {
      const file = files[0];
      if( > 1024 * 1024 *3) {
        alert('File size cannot exceed 3M');
        return;
      } else {
        ("multipartFile", file); 
      }
    }
    this.uploadFile_(formData) // To call the upload interface method  }

3. Problem When the same file is selected again, it is invalid

solve: ( After uploading, execute the following )
this.$refs['upload'].value = ''; // Solve the problem of the second failure of input file
reason:
input file valueThe value is the newly selected value,So select the same file next time,Will not triggerchangeevent

The above are all the relevant knowledge points introduced this time. If you have any questions or supplements, you can contact the editor. Thank you for your support.