Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

download

1. The first method is to create a hyperlink at the front end, and send a GET request to the back-end service through the link of label A to receive the file flow at the back end

<a :href='"/user/downloadExcel"'> Download template </a> Another case is to create a div tag, dynamically create a tag: <div name="downloadfile" onclick="downloadExcel()"> download < / div >function downloadExcel() {
    let a = document.createElement('a')
    a.href ="/user/downloadExcel"a.click(); } There is also a supplementary:function downloadExcel() {
    window.location.href = "/tUserHyRights/downloadUsersUrl";
} 

Copy the code

2. Create an IFrame

<el-button  size="mini" class="filter-item" type="primary" icon="el-icon-download" @click="handleExport(scope.row)"> export < / el - button >/ / method methods:
handleExport(row) {
      var elemIF = document.createElement('iframe')
      elemIF.src = 'user/downloadExcel? snapshotTime=' + formatDate(new Date(row.snapshotTime), 'yyyy-MM-dd hh:mm') +
                    '&category=' + row.category 
      elemIF.style.display = 'none'
      document.body.appendChild(elemIF)
    }
Copy the code

3. Use bloB format for post requests sent from the back-end

var _this = this

      const _searchForm = this.$refs.searchForm.searchForm

      axios({ // The request is adjusted for its own project

        method: 'get'.url: _this.baseUrl + 'prism/satisfaction/downloadTemplate'.responseType: 'blob'.params: { brand: 'xx'.currentDate: _searchForm.currentDate, type: _searchForm.type, category: _searchForm.category },

        headers: {

          'data-type': 'Buffer'.'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'.'token': getToken()

        }

      }).then(res= > {

        const url = window.URL.createObjectURL(new Blob([res.data]))

        const link = document.createElement('a')

        link.style.display = 'none'

        link.href = url

        link.setAttribute('download'.'all_sample_fa_kegg_blast_bst.xls') // Specify the name of the file to be downloaded

        document.body.appendChild(link)

        link.click()

      })

Copy the code

upload

1. The input method

File uploading in VUE consists of two steps: the foreground obtains the file and submits it to the background.

(1) The foreground to obtain files, mainly using the input box to achieve.

<input type="file" ref="clearFile" @change="getFile($event)" multiple="multiplt" class="add-file-right-input" style="margin-left:70px;" accept=".docx,.doc,.pdf">

<el-button type="primary" @click="submitAddFile" size="small">To upload</el-button>
Copy the code

Upload files through the input box of file type. Multiple =”multiplt” and accept are used to restrict the type of uploaded files. Finally, by listening to the change event, the foreground obtains the uploaded file.

getFile(event){
       var file = event.target.files;
       for(var i = 0; i<file.length; i++){// Determine the upload type
           var imgName = file[i].name;
            var idx = imgName.lastIndexOf(".");  
            if(idx ! = -1) {var ext = imgName.substr(idx+1).toUpperCase();   
                ext = ext.toLowerCase( ); 
                 if(ext! ='pdf'&& ext! ='doc'&& ext! ='docx'){

                }else{
                      this.addArr.push(file[i]); }}else{}}}Copy the code

The uploaded file can be retrieved via the event.target.files in the change event, where the type restriction is again applied.

(2) Data submission

After obtaining the file data, you need to submit the data to the background, which can be submitted in FormData mode.

submitAddFile(){
           if(0= =this.addArr.length){
             this.$message({
               type: 'info'.message: 'Please select the file to upload'
             });
             return;
           }

            var formData = new FormData();
            formData.append('num'.this.addType);
            formData.append('linkId'.this.addId);
            formData.append('rfilename'.this.addFileName);
            for(var i=0; i<this.addArr.length; i++){ formData.append('fileUpload'.this.addArr[i]);
            }
          let config = {
            headers: {
              'Content-Type': 'multipart/form-data'.'Authorization': this.token
            }
          };
          this.axios.post(apidate.uploadEnclosure,formData,config)
            .then((response) = > {
                if(response.data.info=="success") {this.$message({
                        type: 'success'.message: 'Attachment uploaded successfully! '}); }})}Copy the code

There are two things to be aware of when submitting data: the formData object and the Content-Type. Once you’ve handled these two things, it’s just like any other interface.

2. el-upload

The implementation principle is much the same.

 <el-upload
 class="upload-demo"
 ref="upload"
 action="doUpload"
 :limit="1"
 :file-list="fileList"
 :before-upload="beforeUpload">
 <el-button slot="trigger" size="small" type="primary">Select the file</el-button>
 <a href="./static/moban.xlsx" rel="external nofollow" download="Template"><el-button size="small" type="success">Download the template</el-button></a><! --<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">Uploading to the server</el-button> -->
 <div slot="tip" class="el-upload__tip">Only excel files can be uploaded, and the maximum size is 5MB</div>
 <div slot="tip" class="el-upload-list__item-name">{{fileName}}</div>
 </el-upload> 
 <span slot="footer" class="dialog-footer">
 <el-button @click="visible = false">cancel</el-button>
 <el-button type="primary" @click="submitUpload()">determine</el-button>
 </span>

Copy the code

Compare file sizes before uploading.

beforeUpload(file){
 this.files = file;
 const extension = file.name.split('. ') [1= = ='xls'
 const extension2 = file.name.split('. ') [1= = ='xlsx'
 const isLt2M = file.size / 1024 / 1024 < 5
 if(! extension && ! extension2) {this.$message.warning('Upload template can only be XLS, XLSX format! ')
  return
 }
 if(! isLt2M) {this.$message.warning('Upload template size cannot exceed 5MB! ')
  return
 }
 this.fileName = file.name;
 return false // Returning false will not automatically upload
 },

Copy the code

Manual upload confirms submission.

submitUpload() {
 debugger
 console.log('upload'+this.files.name)
 if(this.fileName == "") {this.$message.warning('Please select the file to upload! ')
  return false
 }
 let fileFormData = new FormData();
 fileFormData.append('file'.this.files, this.fileName);//filename is the key, file is the value, and test.zip is the filename to be uploaded
 let requestConfig = {
  headers: {
  'Content-Type': 'multipart/form-data'}},this.$http.post(`/basedata/oesmembers/upload? companyId=`+this.company, fileFormData, requestConfig).then((res) = > {
  debugger
  if (data && data.code === 0) {
  this.$message({
  message: 'Operation successful'.type: 'success'.duration: 1500.onClose: () = > {
  this.visible = false
  this.$emit('refreshDataList')}}}else {
  this.$message.error(data.msg)
  }
 }) 
 }
Copy the code