使用REST下载时文件名错误

时间:2016-03-01 16:33:16

标签: java file rest download content-disposition

尝试使用RestFul下载文件时遇到问题。我设置了内容配置和附件,但是当下载文件时,它有一个随机名称。

describe("check something", function() {
    it ("test something", function(done) {
        afterRendered(Template.homepage, function() {
            chai.expect(...).to.not.be.undefined;
            done();
        });
        FlowRouter.go('somewhere');
    });

    it ("test something else", function(done) {
        FlowRouter.go('home');
        var waitUntilOnError = function(done) {
            return function() {
                done("Failed to wait until")
            }
        };
        var test = function() {
            return $('div').length === 1;
        }
        var maxAttempt = 200;
        var waitBetweenAttempt = 60;
        this.timeout(maxAttempt * waitBetweenAttempt * 2);
        waitUntil(test, done, waitUntilOnError, maxAttempt, waitBetweenAttempt);
    });
});

例如,如果文件名是" file001.xls",则响应为:

@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();

但下载的文件名称如下: 8fecd36a-a5aa-4b04-b757-4c38ddea11db.xls

拜托,请帮帮我吧! : - )

1 个答案:

答案 0 :(得分:0)

我已经解决了我的问题。我已将此标题添加到回复中:

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();