介绍
文件下载有2种方式:
- 超链接下载,实现简单,但有缺点
- 通过代码实现下载,实现较复杂,但没有缺点
超链接下载
创建jsp,关键内容如下:
<a href="1.zip">下载1.zip</a><br/>
<a href="1.jpg">下载1.jpg</a><br/>
并将 1.zip 和 1.jpg 放到工程目录下
启动tomcat,访问该jsp
点击 下载1.zip 可能会下载,也可能直接打开,而且是乱码
点击 下载1.jpg 可能会下载,也可能直接打开,可能正常显示图片,也可能是乱码
原因:
tomcat 的设置,在
tomcat-9.0.44\conf\web.xml浏览器的原因,如果浏览器能够打开(如:图片,文本文件),浏览器就直接打开;
如果不能打开,就提示下载
通过代码下载(中文乱码)
实现servlet
@WebServlet(urlPatterns = "/download")
public class DownloadFile extends HttpServlet {
//定义字节数组的长度
static final int BUFF_LEN=1024*8;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
HttpServletRequest request=(HttpServletRequest)req;
HttpServletResponse response=(HttpServletResponse)resp;
String name=request.getParameter("name");
//获取文件的 content type
String mineType=getServletContext().getMimeType(name);
//向浏览器发送 content type
response.setContentType(mineType);
//浏览器能够打开该文件,也不会打开,而是提示下载
response.setHeader("content-disposition", "attachment;filename=" + name);
//获取文件全路径
String path=getServletContext().getRealPath("/file/"+name);
//读取文件流
FileInputStream fis=null;
//获取输出流
ServletOutputStream sos=null;
try{
fis= new FileInputStream(path);
sos=resp.getOutputStream();
byte[] buff=new byte[BUFF_LEN];
//读取一部分文件,然后向浏览器输出一部分,然后循环,一直读取完毕
// int len=fis.read(buff);
// while(len!=-1){
// sos.write(buff,0,len);
// len=fis.read(buff);
// }
//简写
int len=0;
while((len=fis.read(buff))!=-1){
sos.write(buff,0,len);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
fis.close();
sos.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
实现jsp
创建jsp,关键内容如下:
<a href="download?name=1.zip">下载1.zip</a><br>
<a href="download?name=1.png">下载1.png</a><br>
点击下载时,进入 servlet ,通过java代码实现下载
缺点
下载中文文件时,文件名错误
<a href="download?name=测试.zip">下载1.zip</a><br>
通过代码下载(解决中文乱码)
详见 链接