el-upload 上传、预览、和下载

1,117 阅读1分钟

最近碰到个需求是上传文件 点击预览 和 下载。恰好我没写过这方面的,让我纠结了好久啊

image.png

1.上传(采用的是自定义上传 方式)

使用 :http-request

因为下面的文件显示是自定义的我就把el-upload自带的隐藏了

 <el-upload
          ref="upload"
          :limit="1"
          action="string"
          :http-request="fileRequest"
          :before-remove="handleRemove"
          :on-exceed ="handleExceed"
        >
          <el-button slot="trigger" size="small" type="primary" >上传附件</el-button>
        </el-upload>
          <div v-for="(file ,index) in fileList" :key="index" class="file-list">
            <span>{{file.name}} </span> 
           <div>
            <el-button  type="text" size="small" @click="handlePreview(file)">预览</el-button>
            <el-button type="text" size="small" style="color: red;" @click="handleRemove(file)">删除</el-button>
           </div>
        </div>
::v-deep .el-upload-list{
  display: none;
}
.file-list{
  display: flex;
  justify-content: space-between;
  padding-right: 30px;
  margin-top: 10px;
}

文件上传的代码 接口返回的是一个文件路径 所以我就得自己切出来文件名

fileRequest(file){
      let formData = new FormData();
      formData.append("file", file.file); 
      uploadFileApi(formData).then(res=>{
        this.$message.success(res.msg);
        this.url = res.data.fileUrl;
        this.fileList.push({
          name:file.file.name,
          url:this.url
        })
      })
    },

2.预览 直接用的window.open()

    handlePreview(file) {
      try {
        window.open("http://"+file.url, '_blank')
      } catch (error) {
        this.$message.error('解析路径失败!');
      }
      
    },

3.下载

我在这块做了好久啊 主要是一直想的是直接有url了 可以直接下载 但是后来发现下载的文件显示错误

image.png 最后变成了请求 接口下载 后端返回文件流

文件流的长相~  就是这个死样子  然后 因为没返回code  !  拦截器直接拦截了

image.png

但是可以直接在拦截器中设置 没返回code 直接返回res

      let fileName = file.fileName;//文件名
      let url = '/api/file/download?fileName='+fileName ;
      const x = new window.XMLHttpRequest();
      x.open("GET", url, true);
      x.responseType = "blob";
      x.setRequestHeader('token', getToken())
      x.onload = () => {
      const url = window.URL.createObjectURL(x.response);
      const a = document.createElement("a");
      a.href = url;
      a.target = "_blank";
      a.download = fileName;
      a.style.display = "none";
      document.body.append(a);
      a.click();
      };
      x.send();
    },

浅浅记录一下啦 ~ 希望自己有一天可以变成 很厉害的程序员