vue中文件上传和下载使用总结

222 阅读1分钟

上传文件

核心代码

<el-upload class="upload-demo" action="uploadFileUrl" ref="upload" multiple :show-file-list=false :on-change="handleFileChange"
                   :before-upload="beforeUpload">
    <el-button type="primary" size="mini">上传</el-button>
</el-upload>
beforeUpload(file){
	  console.log('===============file'+ file)
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1);
      if ('.pdf'.indexOf(fileSuffix) === -1) {
        this.$message.error('设计资料只能是pdf格式!');
        return false
      }
      let formData = new FormData()
      formData.append('file', this.fileList)
      addWareDocument(formData).then(res => {
        this.$message.success(res.msg)
        this.loadTable()
      })
    },
handleFileChange(file, fileList){
      console.log('===============file'+ file, fileList)
      this.fileList = fileList[0].raw
      this.$refs.upload.clearFiles()
    },    

下载文件

两种方式:
1、直接使用window.open + 文件在服务器的地址
2、创建一个a标签赋予href属性,再点击操作

download(row) {
      console.log('row', row)
      // const a = document.createElement('a')
      // a.setAttribute('download', row.fileName)
      // a.setAttribute('target', '_blank')
      // a.setAttribute('href', row.hostip + row.filePath)
      // a.click()
      window.open(row.hostip + row.filePath)
    },