文件下载
文件下载通常以流的形式上传。
download.jsp文件下载界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="<%=request.getContextPath()%>/download?file=cpt.png">下载</a>
</body>
</html>
FileDownloadServlet
@WebServlet("/download")
public class FileDownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//客户端获取需要下载的文件
String file= req.getParameter("file");
System.out.println(file);
//获取文件在我们项目中的路径,发布到tomcat的实际路径
String path=req.getServletContext().getRealPath("/file/"+file);
System.out.println(path);
FileInputStream fileInputStream=new FileInputStream(path);
resp.setCharacterEncoding("UTF-8");
//指明响应的配置信息,包含附件
resp.setHeader("Content-Disposition","attachment;filename="+file);
//如果文件名不包含中文可以不设置该项
//如果包含中文名,则需要设置编码,否则文件名下载后中文字符会乱码
//getBytes指定了编码的方式,ISO-8859-1指定了解码(读取)的方式,想要转换编码,就是先编码,再解码
//resp.setHeader("Content-Disposition","attachment;filename="+new String(file.getBytes("gb2312"),"iso-8859-1"));
ServletOutputStream servletOutputStream=resp.getOutputStream();
byte[] buf=new byte[1024];
int len;
while((len=fileInputStream.read(buf))!=-1){
servletOutputStream.write(buf,0,len);
}
servletOutputStream.close();
}
}
截图:
注意:(该问题如有解决方法欢迎留言交流相互学习)
1.提交要下载的文件包含中文名的会出现500错误;
1.1错误内容:
1.2代码:
1.3控制台输出:
2.直接在代码里面写入文件名:(文件正常下载,下载的文件也不会出现乱码的情况)
2.1代码:
2.2控制台输出:
2.3效果: