javascript - 如何使用 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();
});
}
我希望下载未损坏的文件,但下载了损坏的文件。
解决方案
推荐阅读
- yup - 在 Yup 中使用 stripUnknown 时如何明确允许附加字段?
- asp.net-mvc - 在一对多关系中应用级联删除
- mysql - 我无法在 mysql 工作台中导入 100 列的 csv 文件。我尝试使用数据导入向导..导入仍然需要时间
- python - Pandas Dataframe.to_csv - 将变量值插入 csv 文件的开头
- .net - Blazor:无法更新选定的下拉列表,而文本框值已更新
- r - 在 RMarkdown 文档中传递多个参数
- database - 从在 Openshift 4.6 上运行的 Spring Boot 应用程序连接外部数据库
- sqlfiddle - 如何在 sql.js 中编写 datediff() - “sql.js 应该具有相同的输出”?
- reactjs - 从子组件关闭 Material UI 对话框会触发父对话框打开
- xaml - 从其 xaml 访问自定义控件的可绑定属性