element一次上传多个文件,并将文件名展示出来;使用文件流进行下载

1.文件批量上传

<el-form-item label="项目资料:" prop="attachmentVos">
	<!-- 上传的文件进行回显 -->
    <div style="display:inline-block;" :key="'p'+pindex">
        <el-tag  v-for="item in ruleForm.attachmentVos" :key="item.uuid?item.uuid:item.id" closable :disable-transitions="false" @close="handleClose(item)" style="margin-right:3px;">
              {{item.name}}
        </el-tag>
    </div>
     <!-- 上传的文件 -->       
    <el-upload class="upload-demo" :style="ruleForm.attachmentVos.length==0?'margin-top: -40px;':''" :ref="`Uploader-${uploadId}`" :name="uploadId" :auto-upload="false" action="#" :http-request="annexUploads" multiple :on-preview="handlePreview" :on-success="handleSuccess" :on-change="changeUpload" :on-remove="handleRemove" :file-list="fileList" accept=".rar,.zip,.wps,.doc,.docx,.pdf,.xls,.xlsx,.jpg" :show-file-list="false">
        <el-button slot="trigger" size="small" type="primary">上传文件</el-button>
        <div slot="tip" class="el-upload__tip">支持文件格式:.rar .zip .wps .doc .docx .pdf .xls .xlsx .jpg</div>
    </el-upload>
</el-form-item>
	  ruleForm: {
        attachmentVos: [],
      },
      fd: new FormData(),//上传的文件
      uploadId: Math.random().toString(36).substr(2).toLocaleUpperCase(),//确保ref为唯一的值
      fileList: [],
      uploadFiles: [], //待上传的文件列表
      fileTotal: 0, //上传文件总数
      pindex: 0,//上传的文件及时回显
      currentUploadNum: 0,//用来判断是否将选中的文件全部上传
 // 附件资料--------开始
    handleSuccess(response, file, fileList) {
      console.log("成功了", response, file, fileList);
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log("file", file);
    },
    changeUpload(file, fileList) {
      console.log("fdsbsgfbsdf", file, fileList, fileList[fileList.length - 1]);
      //获取添加文件进来的状态
      file.status == "ready" && this.uploadFiles.push(file.raw);
      //获取原始文件的个数
      this.fileTotal = document.getElementsByName(this.uploadId)[0].files.length;
      //如果原始文件和upload的个数相同的时候就说明已经添加完了,可以触发上传的方法了
     
     if (this.uploadFiles.length === this.fileTotal) {
        for (let i = 0; i < fileList.length; i++) {
          console.log('fileList[i].type',fileList[i].raw.type);
          console.log('fileList[i]',fileList[i]);
          
          let nameList = fileList[i].name.split('.')
          let getSuffix = nameList[nameList.length - 1]
 		  console.log('fileList[i]名字后缀:', getSuffix);
	      const isXls = getSuffix === "wps" || getSuffix === 'doc' || getSuffix === 'docx' || getSuffix === 'pdf' || getSuffix === 'xls' || getSuffix === 'xlsx' || getSuffix === 'jpg'

            if (!isXls) {
                this.uploadFiles = [];
                this.fileList = [];
                return this.$message.error('文件后缀名必须为.wps/.doc/.docx/.pdf/.xls/.xlsx/.jpg!')
            }
          const isLt10M = fileList[i].size / 1024 / 1024;
          if (isLt10M > 50) {
            this.uploadFiles = [];
            this.fileList = [];
            return this.$message.error("文件大小不能超过 50MB!");
          }
        }
      }
      if (this.uploadFiles.length === this.fileTotal) {
        //获取上传文件的组件
        const Uploader = this.$refs[`Uploader-${this.uploadId}`];
        //触发上传文件列表的方法
        Uploader.submit();
        this.currentUploadNum = 0;
        console.log("this.currentUploadNum", this.currentUploadNum);
      }
    },
    annexUploads(file) {
      console.log("filefilefilefilefile", file);
      // let fd = new FormData();
      this.fd.append("Filedata", file.file);
      console.log("fdfdfdfdfdfdfd", this.fd);
      this.currentUploadNum++;
      //  console.log('this.uploadFiles.length,this.fileTotal',this.currentUploadNum , this.fileTotal);
      if (this.currentUploadNum === this.fileTotal) {
        this.loading = true;
        this.fd.append("type", "1");//多加一个传参
        annexUploads(this.fd)
          .then((res) => {
            if (res.code == "200") {
              this.loading = false;
              this.$message.success("附件上传成功!");
              res.data.forEach((item, index) => {this.ruleForm.attachmentVos.push(item);});
              console.log("this.ruleForm.attachmentVos",this.ruleForm.attachmentVos);
              this.uploadFiles = [];
              this.fileList = [];
              this.fd = new FormData();
            } else {
              this.$message.error(res.message);
            }
          })
          .catch((err) => {
            this.uploadFiles = [];
            this.fd = new FormData();
            this.loading = false;
          });
      }
    },
    // 项目内容--项目资料---删除
    handleClose(tag) {
      this.$confirm("是否确定删除这个文件?", "删除", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
      })
        .then(() => {
          this.ruleForm.attachmentVos.splice(this.ruleForm.attachmentVos.indexOf(tag),1);
          this.pindex++;
          this.$message({type: "success",message: "删除成功",});
        })
        .catch(() => {
          this.$message({type: "info",message: "已取消删除",});
        });
    },
    // 附件资料--------结束
:ref="'Uploader-'+uploadId"
if (this.uploadFiles.length === this.fileTotal) {
        //获取上传文件的组件
       var name = "Uploader-" + this.uploadId
       var Uploader = this.$refs[name];
         //触发上传文件列表的方法
       Uploader.submit();
       this.currentUploadNum = 0;
}

2.下载

2.1直接使用文件下载

export function batchDownFile(params, requestType) {
    return request({
        url: '/fileIo/batchDownFile',
        method: 'GET',
        params,
        requestType,
        responseType: 'blob',
    })
}

request.js

import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 10000 // request timeout
})

service.interceptors.request.use(
    config => {
        let obj = JSON.parse(sessionStorage.getItem("store"))
        if (obj && obj.system.userInfo.token) {
            config.headers['token'] = obj.system.userInfo.token
        }
        if (store.getters.token) {
            config.headers['X-Token'] = getToken()
        }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
    //决定文件流new Blob([res])
    //const res = response.data--------new Blob([res])
    //const res = response--------new Blob([res.data])
        const res = response.data
        console.log("res111", res, response);
        if (res.code == 200) {
            return Promise.resolve(res)
        } else if (res.code == 0) {
            return Promise.resolve(res)
        } else if (res.code == 401) {
            Message.error(res.msg)
            store.dispatch('user/resetToken').then(() => {
                location.reload()
            })
        } else if (res.code == 20000) {
            return Promise.resolve(res)
        } else {
        //注意:下载时工作流此处需要返回res,返回报错信息,文件流下载不下来
            // Message({
            //     message: res.msg,
            //     type: 'error'
            // })
            // return Promise.reject(res)
            return res
        }
    },
    error => {
        console.log('err' + error) // for debug
        console.log("全局-失败的报错信息", error.response)
        Message({
            message: error.response.data.data ? error.response.data.data : error.response.data.message ? error.response.data.message : "接口报错",
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error.response)
    }
)

export default service
    batchDownFile(val,row) {
      let params  = {
          urlList:row.upLoadUrl.join(","),
          zipName: "业务流程清单",
        }
      batchDownFile(params)
        .then((res) => {
          console.log('res', res)
          let url = window.URL.createObjectURL(new Blob([res]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', '清单.docx') // 文件名
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(url)
        })
        .catch((err) => {
        });

    },

2.2 调用后端接口,去访问返回的链接,并进行下载

<a id="a3333" >
      <div style="cursor: pointer; color: #169bd5" v-for="(item, index) in scope.row.appendId" :key="index" @click="appendIdDownLoad(item, 'a3333')">{{ item.name }}</div>
</a>
appendIdDownLoad(row, val) {
      let params = {
        url: row.url
      }
      downFile(params)
        .then(res => {
          // console.log('res', res)
          let url = res.data
          document.getElementById(val).href = res.data
          document.getElementById(val).download = true
          document.getElementById(val).click()
          console.log('this.urlhref', document.getElementById(val))
        })
        .catch(err => { })
    },

2.3文件流进行下载,适配火狐33

<a id="a3333" >
     <div class="search-button"  @click="excelContract">导出</div>
</a>
excelContract() {
    var data = {
      pageNum: this.currentPage,
      pageSize: this.pagesize,
    };
    this.$api.excelContract(data).then((res) => {
      let url = window.URL.createObjectURL(new Blob([res]));
      // let link = document.createElement("a");
      // link.style.display = "none";
      // link.href = url;
      // link.setAttribute("download", "合同台账导出.xlsx"); // 文件名
      // document.body.appendChild(link);
      // link.click();
      // document.body.removeChild(link);
      // window.URL.revokeObjectURL(url);
      document.getElementById('a3333').href = url
      document.getElementById('a3333').download = '导出.xlsx'
      document.getElementById('a3333').click()
    });
},

你可能感兴趣的:(前端开发,javascript,前端,vue.js)