[英]How can I download zip file from controller on client side? Spring boot
I have file.zip
in DB like BLOB
. 我在数据库中有像BLOB
这样的file.zip
。 I want create method in Spring controller for download this file on client side. 我想在Spring控制器中创建方法以在客户端下载此文件。
@RequestMapping(value = "/downloadResolution/{resolutionId}", method = RequestMethod.GET)
public void downloadResolution(@PathVariable("resolutionId") Long resolutionId, HttpServletResponse response) {
Resolution resolution = resolutionService.findOne(resolutionId);
ResolutionArchive resolutionArchive = resolution.getResolutionArchive();
if (resolutionArchive == null) return;
byte[] archive = resolutionArchive.getArchive();
//this byte[] archive - my zip file from db
}
How can I change this methot In order to download this on client side? 我如何更改此methot以便在客户端下载它?
User press download button. 用户按下下载按钮。 Methos get data from DB in byte[] and user can download it. Methos以字节[]的形式从DB中获取数据,用户可以下载它。
EDIT 编辑
I tried solution of @pleft and it work. 我尝试了@pleft的解决方案,它可以工作。 and I knew - I use ajax for call method 而且我知道-我使用ajax作为调用方法
function downloadResolution(resulutionId) {
$.ajax({
type: 'GET',
dataType: "json",
url: '/downloadResolution/' + resulutionId,
success: function (data) {
},
error: function (xhr, str) {
}
});
}
How realize this if I use ajax? 如果我使用ajax,如何实现呢?
You can use the OutputStream
of your HttpServletResponse
to write your archive bytes there. 您可以使用HttpServletResponse
的OutputStream
在此处写入存档字节。
eg 例如
response.setHeader("Content-Disposition", "attachment; filename=file.zip");
response.setHeader("Content-Type", "application/zip");
response.getOutputStream().write(archive);
EDIT 编辑
Sample download 样本下载
@RequestMapping(value = "/downloadResolution/{resolutionId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void downloadResolution(@PathVariable("resolutionId") Long resolutionId, HttpServletResponse response) throws IOException {
String test = "new string test bytes";
response.setHeader("Content-Disposition", "attachment; filename=file.txt");
response.getOutputStream().write(test.getBytes());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.