vue2 下载文件,文件返回文件流

文章介绍了如何在Vue项目中使用el-upload组件进行文件上传,同时根据审批状态设置上传权限,以及处理文件上传、删除和下载操作,使用axios进行接口交互。
摘要由CSDN通过智能技术生成

上传成功返回上传vue

<template>
  <div>
    <el-upload
      ref="upload"
      class="upload-demo"
      drag
      multiple
      action=""
      :auto-upload="true"
      :before-upload="beforeUpload"
      :limit="10"
      :before-remove="beforeRemove"
      :on-preview="handlePreview"
      :on-exceed="handleExceed"
      :file-list="fileList"
      :httpRequest="uploadFile"
      :disabled="rows.approvalStatus === 'shenpizhong' || rows.approvalStatus === 'shenpitongguo'"
    >
      <div v-if="rows.approvalStatus === 'caogao' || rows.approvalStatus === 'shenpijujue' || rows.approvalStatus === 'bohui'">
        <div class="container">
          <i class="el-icon-upload2" />
          <div class="el-upload__text">将文件拖到此处,或<br /><em>点击上传</em></div>
        </div>
        <p class="el-upload__tip">1.最多可上传10个附件,附件大小不得超过8M;</p>
      </div>
      <div v-else>
        <p class="el-upload__tip" style="color: red; font-size: 15px">禁止上传或者删除附件</p>
      </div>
    </el-upload>
  </div>
</template>
<script>
export default {
  data() {
    return {
      fileList: [],
    }
  },
  methods: {
    // 上传文件
    beforeUpload(file) {
      if (!this.handleChangeFile(file, this.fileList)) {
        return false
      }
      const isLt8M = file.size / 1024 / 1024 < 8
      if (!isLt8M) {
        this.$message({
          message: '上传文件大小不能超过8MB',
          type: 'error',
        })
        return false
      }
      return isLt8M
    },
    handleChangeFile(file, fileList) {
      const existFile = fileList.find((f) => f.name === file.name)
      if (existFile) {
        this.$message.error('当前文件已经存在!')
        return false
      }
      return true
    },
    // 删除上传文件
    beforeRemove(file, fileList) {
      if (this.rows.approvalStatus === 'caogao' || this.rows.approvalStatus === 'shenpijujue' || this.rows.approvalStatus === 'bohui') {
        if (file.id) {
          return this.$confirm('将要删除该附件,是否继续', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            const { id } = { ...file }
            // 接口({ id }).then((data) => {
            //   console.log(data, 'delFile')
            //   this.$message({
            //     message: '删除成功',
            //     type: 'success',
            //   })
            //   this.fileList = fileList
            // })
          })
        }
      }
    },
    // 上传文件
    uploadFile(val) {
      const formData = new FormData()
      formData.append('files', val.file)
      formData.append('category', 'opp-stage')
      //   接口(formData).then((res) => {
      //     console.log('上传文件结果===========》', res.data.data)
      //     res.data.data.forEach((item) =>
      //       this.fileList.push({
      //         name: item.attachmentName,
      //         url: item.attachmentPath,
      //         id: item.attachmentId,
      //       })
      //     )
      //     console.log('uploadFile=========>', this.fileList)
      //   })
    },
    // 下载文件
    handlePreview(file) {
      //   if (file.id) 接口(file)
    },
    // 选取文件超过数量提示
    handleExceed() {
      this.$message({ type: 'error', message: '最多支持10个附件上传' })
    },
    // 回显
    foundationFn(item) {
      this.$nextTick(() => {
        const params = {
          id: this.$route.query.projectId,
          stageCode: item,
        }
        // 接口(params).then((res) => {
        //   this.fileList = res.meetRecordList
        //     ? res.meetRecordList.map((item) => {
        //         return {
        //           name: item.attachmentName,
        //           url: item.attachmentPath,
        //           id: item.attachmentId,
        //         }
        //       })
        //     : []
        // })
      })
    },
  },
}
</script>
<style scoped>
.card-container {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
<style lang="scss" scoped>
.upload-demo {
  ::v-deep .el-upload-dragger {
    width: 619px;
    height: 84px;
    line-height: 17px;
    display: flex;
    border: 1px solid #d0d2d7;
    justify-content: space-around;
    align-items: center;

    .container {
      display: flex;
      align-items: center;
    }

    .el-upload__text {
      font-size: 12px;
      text-align: start;
    }

    i {
      font-size: 20px;
      margin: 0 5px 0;
    }
  }
}
</style>

接口

axios

import axios from 'axios'
export function get(url, params, config) {
  return axios
    .get(url, {
      ...config,
      params,
    })
    .then((respose) => {
      if (config && (config.fullResponse === true || config.fullResponse === 'custom')) {
        return respose.data
      }
      return respose.data.data
    })
}

export function post(url, data, config) {
  return axios.post(url, data, config).then((respose) => {
    if (config && (config.fullResponse === true || config.fullResponse === 'custom')) {
      return respose.data
    }
    return respose.data.data
  })
}

export function del(url, config) {
  return axios.delete(url, config).then((respose) => {
    return respose.data.data
  })
}

const handelBlobResponse = (response) => {
  const href = URL.createObjectURL(response.data)
  const a = document.createElement('a')
  a.style.display = 'none'
  let filename = ''
  const content = response.headers['content-disposition'] // 注意是全小写,自定义的header也是全小写

  if (content) {
    filename = content
      .split(';')
      .map((item) => {
        const [key, value = ''] = item.split('=')
        return { key: key.trim(), value: value.trim() }
      })
      .filter((item) => item.key === 'filename' || item.key === 'fileName')
      .map((item) => decodeURIComponent(item.value))[0]
  }
  a.download = filename
  a.href = href
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

/**
 * get请求下载文件
 */
export function download(url, params, config) {
  return axios
    .get(url, {
      ...config,
      params,
      responseType: 'blob',
    })
    .then(handelBlobResponse)
}

/**
 * post请求下载文件
 */
export function postDownload(url, data, config) {
  return axios.post(url, data, {
    ...config,
 
  })

}

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用浏览器的原生下载功能来实现文件下载,具体步骤如下: 1. 在后端根据需要下载文件生成文件,并设置响应头,使其以的形式返回前端。 ``` // Node.js 代码示例 const fs = require('fs') const path = require('path') const filePath = path.resolve(__dirname, './test.pdf') // 返回文件 const stream = fs.createReadStream(filePath) res.setHeader('Content-Type', 'application/octet-stream') res.setHeader('Content-Disposition', 'attachment; filename=test.pdf') stream.pipe(res) ``` 2. 在前端使用`window.URL.createObjectURL`方法将文件转换为 Blob 对象,并创建一个下载链接。 ``` // Vue.js 代码示例 downloadFile() { axios({ url: '/download', method: 'get', responseType: 'blob' }).then(response => { const blob = new Blob([response.data], { type: 'application/octet-stream' }) const url = window.URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.setAttribute('download', 'test.pdf') document.body.appendChild(link) link.click() document.body.removeChild(link) }) } ``` 3. 点击下载链接,浏览器会弹出文件下载对话框,用户选择保存文件的位置即可完成文件下载。 需要注意的是,由于 Blob 对象占用内存较大,如果需要下载文件较大或同时下载多个文件时,可能会导致浏览器卡顿或崩溃。为了避免这种情况,可以考虑使用服务端直接返回文件下载链接,而不是文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值