gpt4 book ai didi

java - jsp safari浏览器windows文件下载内容配置文件名变成-

转载 作者:行者123 更新时间:2023-11-28 22:16:44 24 4
gpt4 key购买 nike

以下代码用于下载附件编码中文字符作为文件名。

w_inf_src = new File(p_filepath);
w_inf = new FileInputStream(w_inf_src);
p_response.setContentType(w_mime+";charset=UTF-8");
p_response.setContentLength(new Long(w_inf_src.length()).intValue());
p_response.setCharacterEncoding("UTF-8");
p_request.setCharacterEncoding("UTF-8");

p_response.setHeader("Content-disposition",
"attachment;filename=\"" + (new java.net.URI(null, null, p_request, p_filename, null)).toASCIIString() + "\"");


// Download File In Progress
w_outf = p_response.getOutputStream();
w_bof = new BufferedOutputStream(w_outf);
while ( (w_bytes_read = w_inf.read(w_buffer, 0, w_buffer.length)) != -1)
w_bof.write(w_buffer, 0, w_bytes_read);
w_bof.flush();

我也试过filename*=UTF-8'' 但是不行

最佳答案

如果您至少使用 java 7 和 Sevlet API 3.0,这是要走的路:

File w_inf_src = new File(p_filepath);
String encoding = StandardCharsets.UTF_8.name();
String w_disposition = String.format("%s;filename=\"%3$s\"; filename*=%2$s''%3$s",
Part.ATTACHMENT,
encoding,
URLEncoder.encode(p_filename, encoding).replace("+", "%20"));

p_response.setContentType(w_mime);
p_response.setContentLengthLong(w_inf_src.length());
p_response.setCharacterEncoding(encoding);
p_response.setHeader("Content-Disposition", w_disposition);

byte[] w_buffer = new byte[p_response.getBufferSize()];
try(FileInputStream w_inf = new FileInputStream(w_inf_src);
OutputStream w_outf = p_response.getOutputStream())
{
int n;
while((n = w_inf.read(w_buffer)) != -1)
{
w_outf.write(w_buffer, 0, n);
}
}

一些注意事项:

  1. 这是您将获得的最准确的处置表格,因为它经过了urlencoded空间净化
  2. content-typecontent-encoding 中设置编码是多余的
  3. 设置请求编码是多余的:你不是在阅读。
  4. 使用 BufferedInputStream 是多余的,因为响应有一个内部缓冲
  5. 使用您自己的最大可用大小的缓冲区 (respose.getBufferSize())
  6. 尽可能使用try-with-resources(如果您使用的是 Java 7+)
  7. 如果您使用的是 Servlet API 3.0+,您有 response.setContentLengthLong(),他们终于明白整数是不够的
  8. 或者使用:response.setHeader("Content-Length", String.valueOf(w_inf_src.length()));:这确保大长度不会被切割成 int 大小

关于java - jsp safari浏览器windows文件下载内容配置文件名变成-,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44668728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com