我在尝试使用 RestFul 下载文件时遇到问题。我正在设置内容处置和附件,但是当下载文件时,它有一个随机名称。
@GET
@Path("{type}/xls")
@Produces("application/vnd.ms-excel")
public Response downloadExcel(@Context HttpHeaders headers...) {
...
File file = getFileToDownload();
Response.ResponseBuilder builder = Response.ok(file);
String fileName = file.getName();
builder.header("Content-Disposition", "attachment; filename=" + fileName);
...
return builder.build();
例如,如果文件名为"file001.xls",则响应为:
Response-Code: 200
Content-Type: application/vnd.ms-excel
Headers: {Content-Disposition=[attachment; filename=file001.xls], Content-Type=[application/vnd.ms-excel], Date=[Tue, 01 Mar 2016 16:18:19 GMT]}
但是下载的文件是这样命名的:8fecd36a-a5aa-4b04-b757-4c38ddea11db.xls
你能帮帮我吗! :-)
我已经解决了我的问题。我已将此标头添加到响应中:
builder.header("Access-Control-Expose-Headers", "Content-Disposition");
并以这种方式在客户端检索响应:
var contentDisposition = response.headers('Content-Disposition');
var initName = contentDisposition.indexOf('filename=') + 9;
var fileName = contentDisposition.substring(initName);
var blob = new Blob([response.data], {type: type});
var blobURL = URL.createObjectURL(blob);
var anchor = document.createElement("a");
anchor.download = fileName;
anchor.href = blobURL;
anchor.click();