String dir = this.getClass().getClassLoader().getResource("/").getPath()+"test.pdf";
File file=new File(dir);
String fileName=file.getName();
String ext=fileName.substring(fileName.lastIndexOf(".")+1);
String agent=(String)request.getHeader("USER-AGENT"); //判断浏览器类型
BufferedInputStream bis=null;
OutputStream os=null;
try {
if(agent!=null && agent.indexOf("Fireforx")!=-1) {
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1"); //防止输出文件名乱码
}
else {
fileName=URLEncoder.encode(fileName,"UTF-8");
}
response.reset();
response.setCharacterEncoding("utf-8");
if(ext=="docx") {
response.setContentType("application/msword"); // word格式
}else if(ext=="pdf") {
response.setContentType("application/pdf"); // pdf格式
}
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
bis=new BufferedInputStream(new FileInputStream(file));
byte[] b=new byte[bis.available()+1000];
int i=0;
os = response.getOutputStream(); //下载
while((i=bis.read(b))!=-1) {
os.write(b, 0, i);
}
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(os!=null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
标签:java,String,示例,fileName,new,null,os,response,下载
来源: https://blog.csdn.net/weixin_37728231/article/details/90373159