文件名非中文下载设置
private void download1(HttpServletResponse response)
throws FileNotFoundException, IOException {
String realpath = this.getServletContext().getRealPath("/download/1.jpg");
String filename = realpath.substring(realpath.lastIndexOf("\\")+1);
response.setHeader("Content-disposition", "attachment;filename=" + filename);
FileInputStream in = new FileInputStream(realpath);
int len = 0;
byte buffer[] = new byte[1024];
OutputStream out = response.getOutputStream();
while ((len = in.read(buffer))>0){
out.write(buffer, 0, len);
}
in.close();
}
文件为中文的下载设置
//中文文件下载,需要用URL编码
private void download2(HttpServletResponse response)
throws FileNotFoundException, IOException {
String realpath = this.getServletContext().getRealPath("/download/图片.jpg");
String filename = realpath.substring(realpath.lastIndexOf("\\")+1);
//URLEncoding URL编码
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename,"UTF-8"));
FileInputStream in = new FileInputStream(realpath);
int len = 0;
byte buffer[] = new byte[1024];
OutputStream out = response.getOutputStream();
while ((len = in.read(buffer))>0){
out.write(buffer, 0, len);
}
in.close();
}
网友评论