0
点赞
收藏
分享

微信扫一扫

antd的upload组件的各种上传、下载操作(vue)

作为前端小白刚刚接触上传、下载文件的操作也让我很头疼,所以利用时间记录一下方便巩固,希望能够帮到大家。

我将情况分为以下几种:

一、点击按钮上传单个文件

//html
<a-upload
                :action="baseUrl + '/api/uploadSingleFile'" 
                :headers="headers"
                :file-list="fileList"
                @change="handleChange_file">
                <a-button>
                  <a-icon type="upload" /> 上传文件
                </a-button>
</a-upload>
//action表示上传的地址,baseUrl是我们公司服务器的IP地址,加上后面的接口地址就组成了完整的上传地址
//headers表示设置上传的请求头部,因为是后台管理系统所以会在里面存放必要的token
//file-list 就是我们上传文件的数组,一个文件就是一个数组元素
//@change就是提交文件的回调
 
 
//data
{
  baseUrl: baseUrl,
  headers: { accesstoken: sessionStorage.getItem("accessToken") },
  fileList:[],
  fileList2:[]
}
//这里除了fileList要需要fileList2的原因是:如果上传按钮下需要展示文件列表就必须是
{
   url: res,
   status: "done",
   name: res,
   uid: index + 1,
}
的对象形式,我们用fileList2来存储文件的下载链接也就是fileList中url的res
 
//methods
    handleChange_file(info) {
      let fileList = [...info.fileList];
      //这一行用来决定上传文件的限制个数,-1就表示1个,-2就是2个依次类推...
      fileList = fileList.slice(-1);
      //这里判断文件是否上传成功
      if (info.file.status === "done") {
        //判断是否正确链接上传地址
        if (info.file.response.code == 0) {
          let arr = fileList;
          this.fileList2 = [];
          //上传成功会把接口返回的下载链接存入fileList2
          arr.forEach((item) => {
            if (item.url) {
            this.fileList2.push(item.url);
          } else if (item.response) {
            this.fileList2.push(item.response.data);
          }
          });
          this.$message.success(`${info.file.name} 上传成功!`);
        }
        //如果是移除文件也会重新填入fileList2
      } else if (info.file.status === "removed") {
        let arr = fileList;
        this.fileList2 = [];
        arr.forEach((item) => {
           if (item.url) {
            this.fileList2.push(item.url);
          } else if (item.response) {
            this.fileList2.push(item.response.data);
          }
        });
      }
      this.fileList = [...fileList]; //重点
    },

二、点击按钮上传多个文件

上面就说过了,把filelist中的数字换一下就行了。

三、上传单个按钮但是不想显示文件列表

antd会像这样上传成功后自动生成列表,但是有时候我们不需要,我们在a-upload下填入

:showUploadList="false"  属性就可以了

四、下载文件(单个)

一般通过动态创建a标签,给url的地址改为文件下载地址就可以了

const a = document.createElement("a");
          a.href = record.filePath;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);

五、下载文件(多个)

一般是通过upload组件把文件列表展示出来,这样一点击就可以下载了

clickModel(record) {
      this.visible = true;
      this.fileList = [];
      let arr = record.filePath;
      arr.forEach((res, index) => {
        this.fileList.push({
          url: res,
          status: "done",
          name: res,
          uid: index + 1,
        });
      });
    },
//这里调用的是a-modal的回调让modal悬浮框显示出来同时,在文件列表中放入我们需要的文件。
//一定要严格按照 url + status + name + uid 的格式。




举报

相关推荐

0 条评论