我有一个用例,在写入 http 响应输出流后,我必须设置“内容类型”和“内容处置”,而不是作为文件下载。以下示例代码描述了这种情况:-
@Context
HttpServletResponse response;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String downloadFile() throws IOException {
File file = new File("/var/tmp/input.txt");
FileInputStream fs = new FileInputStream(file);
copyStream(fs, response.getOutputStream());
response.setContentType("text/csv");
response.setHeader("Content-Disposition","attachment;filename=\"" + "ts.csv" + "\"");
return "";
}
当我提供较小的输入(input.txt 文件)时,我的浏览器会提供下载它的选项,但当输入较大时,它会直接在浏览器选项卡中打印文件内容。
有什么指示我可以做些什么,以便它也为大输入提供文件下载选项吗?
最佳答案
根据 ServletResponse.setContentType 的文档:
Sets the content type of the response being sent to the client, if the response has not been committed yet.
并且,根据 ServletResponse.getWriter 的文档:
Returns a PrintWriter object that can send character text to the client.
在您的编码中,您在设置内容类型
之前将内容写入响应
对象。
为了使自定义内容类型正常工作,您不应该写入响应输出流。
更改您的代码:
copyStream(fs, response.getOutputStream());
response.setContentType( "text/csv" );
response.setHeader( "Content-Disposition",
"attachment;filename=\"" + "ts.csv" + "\"" );
致:
response.setContentType( "text/csv" );
response.setHeader( "Content-Disposition",
"attachment;filename=\"" + "ts.csv" + "\"" );
copyStream(fs, response.getOutputStream());
关于java - 如果在写入 http "Content-type"输出流后设置了 "content-disposition"和 "response",则 http 响应将在浏览器中打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22496258/