我们有一个遗留代码,允许站点用户从服务器下载文件。
到目前为止,下载的文件是
CSV
我们没有问题。
现在服务器还有一个zip文件,其中包含CSV。
服务器正确生成zip文件(
used this tutorial
)及
在服务器中,我们可以打开zip文件,并正确提取内部CSV文件
.
问题在于浏览器下载zip文件时:内部CSV文件没有CSV后缀,无法打开。
我们得到的错误(使用7Zip):
数据意外结束
警告:
标题错误
有效载荷数据结束后有一些数据
后端代码
用于提供文件(正在运行)
Spark-Java
微服务):
public Object handle(Request request, Response response) throws Exception {
fileName = ...
response.raw().setContentType("application/zip");
response.raw().setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
try (
FileInputStream fis = new FileInputStream(fileName);
BufferedOutputStream bufferedOutputStream = new BufferedOutptStream(response.raw().getOutputStream());
BufferedInputStream bufferedInputStream = new BufferedInputStream(fis)) {
ByteStreams.copy(bufferedInputStream, bufferedOutputStream);
} catch (Exception e) {
....
}
return response.raw();
}
前端
获取文件的代码(1):
$scope.downloadFile = function (fileName) {
$http.get(fileName).
success(function (data, status, headers, config) {
var anchor = angular.element('<a/>');
var headers = headers();
var filename = headers['x-filename'];
var contentType = headers['content-type']
data = new Blob([data], {type: contentType});
var fileUrl = URL.createObjectURL(data);
anchor.attr({
'href': fileUrl,
'target': '_blank',
'download': fileName
})[0].click();
}).error(function (data, status, headers, config) {
$log.info("download " + fileName + " error " + status);
}
);
};