setHeader 不改变文件名

setHeader does not change file name

当我使用文件名变量来设置下载文件的名称时,它看不到该变量。但是如果我不为文件名使用变量,那么它会根据需要设置名称。

response().setHeader("Content-disposition", "attachment; filename=testName.pdf"); 这样下载的文件名为testName.pdf

我尝试了三种不同的方法来将它与变量一起使用。

response().setHeader("Content-disposition", "attachment; filename="+ fileName.toString() +".pdf");

..... "attachment; filename="+ fileName +".pdf");

..... "attachment; filename="+ fileName.toString() +".pdf");

完整代码:

public static Result download(String id) throws IOException {
        Get g = new Get(Bytes.toBytes(id));
        g.addColumn(Bytes.toBytes("content"), Bytes.toBytes("raw"));
        g.addColumn(Bytes.toBytes("book"), Bytes.toBytes("title"));

        HTable hTable = new HTable(hConn.config, "books");
        org.apache.hadoop.hbase.client.Result result = hTable.get(g);

        if (result.containsColumn(Bytes.toBytes("content"), Bytes.toBytes("raw"))){
            byte[] rawBook = result.getNoVersionMap().get(Bytes.toBytes("content")).get(Bytes.toBytes("raw"));
            byte[] fileName = result.getNoVersionMap().get(Bytes.toBytes("book")).get(Bytes.toBytes("title"));
            response().setContentType("application/octet-stream");
            response().setHeader("Content-disposition", "attachment; filename=\"" + fileName + "\".pdf");
            return ok(rawBook);
        }
        return notFound();
    }

所以,这是来自 Java Play Framework。数据库是HBase。我有一个名为 books 的 table,它有两个家族 contentbookcontent 包含 pdf 的内容(以字节为单位),book 包含 pdf 的一些属性(标题、页码、作者等)。 contentbookRow Key 是一样的。

是否有另一种使用变量设置文件名的方法,还是我遗漏了什么?

看起来问题在于将 byte[] 转换为 String。该数组上的一个简单的 toString() 将导致类似 [B@186b085 的结果 - 这是 AFAIK 不被接受为 filename 此处。

尝试将 byte[] 转换为 String,如下所示:

String fn = new String(filename, "UTF-8");

请注意,编码始终很重要,但使用此构造函数您将不得不抓住 UnsupportedEncodingException

在 Java 8 中你可以使用下面的代码,而不必赶上 UnsupportedEncodingException:

String fn = new String(filename, java.nio.charset.StandardCharsets.UTF_8);