利⽤response和HttP中的Content-Disposition:attachme。。。中⽂名称的⽂件下载需要注意的问题:
1、在设置response响应为Content-Disposition: attachment; filename=aaa.zip,通知浏览器以下载的⽅式处理服务器发来的数据。
2、对于中⽂名称的⽂件,需要利⽤de(filename,"utf-8"),对中⽂进⾏编码,即可
完整的⽂件下载程序如下package com.baowei.servlet import java.io.FileInputStream;import java.io.FileNotFoundException;import
java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.URLEncoder;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.baowei.persondao.PersonDao;
public class FristServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
fileDownload(resp);
}url编码和utf8区别
private void fileDownload(HttpServletResponse resp) throws IOException {
ServletContext context = ServletContext();
String realpath = RealPath("/哈哈.png");
String filename = realpath.substring(realpath.lastIndexOf("\\") + 1);
System.out.println(filename);
// resp.setContentType("image/png"); ,⽤于图⽚的显⽰
/
/中⽂的⽂件名需要进⾏de(filename,"utf-8")的处理
resp.setHeader("Content-Disposition", "attachment;filename="+de(filename,"utf-8"));
FileInputStream is = new FileInputStream(realpath);
byte[] buffer = new byte[1024];
int len = 0;
OutputStream out = OutputStream();
while ((len = is.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
is.close();
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。