转载
2015-09-14 12:24:55
两种实现方法: 一:通过超链接实现下载
在HTML网页中,通过超链接链接到要下载的文件的地址,程序运行后,可以通过单击需要下载文档实现下载
但是这里会出现一个问题,就是单击下载压缩包的时候会弹出下载页面,但是下载图片的时候浏览器就直接打开了图片,没有下载。
这是因为通过超链接下载文件时,如果浏览器可以识别该文件格式,浏览器就会直接打开。只有浏览器不能识别该文件格式的时候,才会实现下载。
因此利用第二种方法实现下载功能。
二:通过Servlet程序实现下载
通过Servlet下载文件的原理是通过servlet读取目标程序,将资源返回客户端。
[html]
<</span>h1>通过链接下载文件</</span>h1>
<</span>a href="/day06/download/cors.zip">压缩包
<</span>h1>通过servlet程序下载文件
压缩包
其中,/day06/ServletDownload 是servlet程序的映射路径
然后新建一个servlet,名称为ServletDownload,URL映射为/ServletDownload
添加代码如下:
[java]
@WebServlet(asyncSupported = true, urlPatterns = { "/ServletDownload" })
public class ServletDownload extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletDownload() { super();
// TODO Auto-generated constructor stub }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub //获得请求文件名
String filename = request.getParameter("filename"); System.out.println(filename); //设置文件MIME类型 response.setContentType(getServletContext().getMimeType(filename));
//设置Content-Disposition
response.setHeader("Content-Disposition", "attachment;filename="+filename); //读取目标文件,通过response将目标文件写到客户端
//获取目标文件的绝对路径
String fullFileName = getServletContext().getRealPath("/download/" + filename); //System.out.println(fullFileName); //读取文件
InputStream in = new FileInputStream(fullFileName);
OutputStream out = response.getOutputStream(); //写文件
int b;
while((b=in.read())!= -1)
{ out.write(b); }
in.close();
out.close(); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub }
}
重启tomcat服务器,即可实现对压缩包和对图片的下载。
<转>java web文件下载功能实现
猜你喜欢
转载自rourou61.iteye.com/blog/2322874
今日推荐
周排行