如何使用angular和springbot下载文件

时间:2019-02-15 14:25:04

标签: javascript angular spring-boot download

我正在尝试下载文件(该文件可以具有各种扩展名,而不仅仅是特定的扩展名)。我从服务器上确实收到了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();
        });
}

我希望下载的文件没有损坏,但是下载了损坏的文件。

0 个答案:

没有答案
相关问题