java + vue.js + elementUI 文件下载

最近项目用到了下载,但是前端不熟悉 搞了我很久,特此记录下来。

在网上搜了 很多  都说直接用 a 标签  不知道为什么我的不可以 。

于是 我只能 传给前端base64文件 然后 前端 用 base64文件 转。

话不多说 ,直接上代码

首先后端代码 :

    @GetMapping("/download/{id}")
    public ResponseResult downloadAttachment(@PathVariable(name = "id")Long id) {
        TbAttachment tbAttachment = tbProjectService.getTbAttachmentById(id);
        if(tbAttachment==null){
            return ResponseResult.error(404,"文件不存在");
        }
        String filePath = tbAttachment.getFilePath();
        File file = new File(filePath);
        if(file.exists()){
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                byte[] bytesArr = IOUtils.toByteArray(fis);
                String result = Base64.encodeBase64String(bytesArr);
                return ResponseResult.success("操作成功",result);
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseResult.error(500,"服务器错误");
            }
        }
        return ResponseResult.error(404,"文件不存在");

前端代码:



//因为会有多个文件要下载,所以我这里是循环创建
<el-col :span="24">
            <el-form-item label="附件:">
              <el-button
                v-for="(item, index) in form.attachments"
                :key="index"
                type="text"
                style="color:#409EFF"
                @click="download_attachment(item)"
              >{{ index == form.attachments.length-1 && item.fileName || (item.fileName + '、') }}</el-button>
            </el-form-item>
</el-col>


    //1个是按钮调用的 方法,1个是 base64字符串转化代码
    download_attachment(item) {
      downloadAttachment(item).then(response => {
        console.log(response.data);
        const blob = this.b64toBlob(response.data,this.getBlobType(item.fileName));
        const fileName = item.fileName;
        const elink = document.createElement("a");
        elink.download = fileName;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      });
    },
    b64toBlob(b64Data,  contentType = "", sliceSize = 512) {
      const byteCharacters = atob(b64Data);
      const byteArrays = [];
      for (
        let offset = 0;
        offset < byteCharacters.length;
        offset += sliceSize
      ) {
        const slice = byteCharacters.slice(offset, offset + sliceSize);
        const byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i += 1) {
          byteNumbers[i] = slice.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
      }

      const blob = new Blob(byteArrays, { type: contentType });
      return blob;
    },
    
    //获取文件类型,不然的话所有文件都会下载成txt
    getBlobType(name) {
      const index = name.lastIndexOf(".");
      let type = "";
      let fileType = name.substring(index + 1, name.length);
      if (fileType === "png") {
        type = "image/png";
      } else if (fileType === "jpg") {
        type = "image/jpeg";
      } else if (fileType === "tar") {
        type = "application/x-tar";
      } else if (fileType === "zip") {
        type = "application/zip";
      } else if (fileType === "tgz") {
        type = "application/x-compressed";
      } else if (fileType === "gif") {
        type = "image/gif";
      } else if (fileType === "rar") {
        type = "application/x-rar-compressed";
      } else if (fileType === "rtf") {
        type = "application/rtf";
      } else if (fileType === "xls") {
        type = "application/vnd.ms-excel";
      } else if (fileType === "docx") {
        type =
          "application/vnd.ms-excelapplication/vnd.openxmlformats-officedocument.wordprocessingml.document";
      } else if (fileType === "xlsx") {
        type =
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      } else if (fileType === "pptx") {
        type =
          "application/vnd.openxmlformats-officedocument.presentationml.presentation";
      } else if (fileType === "ppt") {
        type = "application/vnd.ms-powerpoint";
      } else if (fileType === "xls") {
        type = "application/vnd.ms-excel";
      } else if (fileType === "doc") {
        type = "application/msword";
      } else {
        type = "text/plain";
      }

      return type;
    }

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值