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;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章