二进制内容响应-无效的文件名?

时间:2019-07-08 11:50:14

标签: java servlets binary response

我正在尝试在我的Java Servlet中提供二进制响应。首先,我从数据库获取请求的数据,然后尝试将其设置为如下响应:

    ResultSet rset = (ResultSet) stmt.executeQuery();

    if (rset.next())
    {
      byte[] bData = rset.getBytes("Soubor");
      String sJmenoSouboru = rset.getString("Jmeno_souboru");

      response.setHeader("Content-Disposition","attachment;filename=" + sJmenoSouboru);
      //response.setHeader("Content-Description", sJmenoSouboru);
      response.setHeader("Content-Transfer-Encoding", "binary");
      //response.setContentType("application/pdf");
      response.setContentType("application/octet-stream");

      ServletOutputStream hOutStream = response.getOutputStream();
      hOutStream.write(bData);
      hOutStream.flush();
      hOutStream.close();
    }

这很好用,直到文件名中有'§'字符为止。比我得到ERR_SPDY_PROTOCOL_ERROR。据我所知,提到的字符应该在文件名中可用。有人知道,问题可能出在哪里?

1 个答案:

答案 0 :(得分:0)

正如评论中的stdunbar所述,问题在于'§'是非ASCII字符,需要在文件名中转义。我通过更改以下代码行解决了该问题:

String sJmenoSouboru = URLEncoder.encode(rset.getString("Jmeno_souboru"), StandardCharsets.UTF_8.toString());