【发布时间】:2016-01-13 00:56:12
【问题描述】:
我的问题是我在客户端获取了错误大小的文件。这是我的@Controller ...
@RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
public ResponseEntity<?> download(final HttpServletRequest request,
final HttpServletResponse response,
@PathVariable("id") final int id) throws IOException {
try {
// Pseudo-code for retrieving file from ID.
Path zippath = getZipFile(id);
if (!Files.exists(zippath)) {
throw new IOException("File not found.");
}
ResponseEntity<InputStreamResource> result;
return ResponseEntity.ok()
.contentLength(Files.size(zippath))
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new InputStreamResource(new FileInputStream(zippath.toFile())));
} catch (Exception ex) {
// ErrorInfo is another class, unimportant
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ErrorInfo(ex));
}
}
...这是我使用 angular-file-saver 的客户端代码...
$http({url: "export/download/" + exportitem.exportId, withCredentials: true})
.then(function(response) {
function str2bytes(str) {
var bytes = new Uint8Array(str.length);
for (var i=0; i<str.length; i++) {
bytes[i] = str.charCodeAt(i);
}
return bytes;
}
var blob = new Blob([str2bytes(response.data)], {type: 'application/octet-stream'});
FileSaver.saveAs(blob, "download.zip");
}, $exceptionHandler);
原始文件为 935673 字节,但 response.data 为 900728,并将其通过转换传递给 Uint8Array 会产生一个大小为 900728 的 Blob。无论哪种方式,生成的保存文件都是 900728 字节(34945 字节)。此外,它所写的内容也不完全相同。它似乎有点臃肿,但最后一部分似乎被截断了。有什么想法我可能做错了吗?
更新
我刚刚将我的控制器方法更新为以下并得到完全相同的结果。咕噜。
@RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
public void download(final HttpServletRequest request,
final HttpServletResponse response,
@PathVariable("id") final int id) throws IOException {
// Pseudo-code for retrieving file from ID.
Path zippath = getZipFile(id);
if (!Files.exists(zippath)) {
throw new IOException("File not found.");
}
response.setContentType("application/zip");
response.setHeader("Content-Disposition",
"attachment; filename=download.zip");
InputStream inputStream = new FileInputStream(zippath.toFile());
org.apache.commons.io.IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
inputStream.close();
}
【问题讨论】:
-
zippath.toFile()会发生什么? -
将 Path 对象转换为 File 对象,以便我可以在 FileInputStream 中使用它。
标签: java angularjs spring zipfile