首页 > 解决方案 > 如何使用 Angular 和 Spring Boot 下载文件

问题描述

我正在尝试下载一个文件(该文件可以有各种扩展名,而不仅仅是一个特定的扩展名)。我确实从服务器收到了 byte[] 数组,但在客户端,文件损坏了。

我尝试过 1. 从服务器发送资源文件 2. 从服务器发送 InputStream 文件

这是来自 myBatis 的代码,SQL

<resultMap id="downloadAttachmentMap" type="Document">
    <result column="id" property="id"/>
    <result column="fileName" property="fileName"/>
    <result column="docFile" property="docFile" javaType="_byte[]" jdbcType="BLOB" typeHandler="org.apache.ibatis.type.ByteArrayTypeHandler"/>
</resultMap>

<select id="downloadDocumentById" resultMap="downloadAttachmentMap" parameterType="Long">
         SELECT td.id,
           TD.DOC_FILE_NAME      fileName,
           td.DOC_FILE            docFile
    FROM TAB_DOCUMENTS td
    WHERE td.id = #{docId}

</select>

控制器方法,它返回一个 Document 对象,该对象具有 byte[] 类型的字段。

  @GetMapping(value = "/download-document/{id}")
   public Document downloadEmpDocument(@PathVariable Long id) {
      Document doc =  employeeService.downloadDocument(id);
      return doc;
  }

这是来自客户端服务的方法:

 downloadEmpDocument(docId: number): Observable<Document>{
       return this
           .http
           .get<Document>(`${this.envConfig.baseUrl}/employee/download-document/${docId}`);
}

最后,这是来自客户端的方法,我试图下载知道其 ID 的文件。

downloadDocument(document: Document) {
    this.employeeService.downloadEmpDocument(document.id)
        .subscribe(doc => {
        const blob = new Blob([doc.docFile], {type:  "attachment; filename=\""+doc.filename+"\""});

         var link = document.createElement('a');
         link.href = window.URL.createObjectURL(blob);
         link.download = doc.fileName;
         link.click();
        });
}

我希望下载未损坏的文件,但下载了损坏的文件。

标签: javascriptangularspring-bootdownload

解决方案


推荐阅读