java web response提供文件下载功能的实例讲解
程序员文章站
2023-12-15 18:16:28
webapp项目的结构如下图:
download.html文件的内容如下:
<...
webapp项目的结构如下图:
download.html文件的内容如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>insert title here</title> </head> <body> <h1>资源下载:</h1> <p> 单纯地使用a标签时,只有浏览器不能解析的文件才会是下载,否则将被浏览器直接解析。</p> <a href="/web/resource/a.mp3" rel="external nofollow" >a.mp3</a><br> <a href="/web/resource/a.exe" rel="external nofollow" >a.exe</a><br> <a href="/web/resource/a.txt" rel="external nofollow" >a.txt</a><br> <a href="/web/resource/a.xlsx" rel="external nofollow" >a.xlsx</a><br> <a href="/web/resource/a.png" rel="external nofollow" >a.png</a><br> <p>因此,使用a标签结合servlet的response指示浏览器不解析这些待下载文件</p> <a href="/web/download?filename=a.mp3" rel="external nofollow" >a.mp3</a><br> <a href="/web/download?filename=a.exe" rel="external nofollow" >a.exe</a><br> <a href="/web/download?filename=a.txt" rel="external nofollow" >a.txt</a><br> <a href="/web/download?filename=a.xlsx" rel="external nofollow" >a.xlsx</a><br> <a href="/web/download?filename=a.png" rel="external nofollow" >a.png</a><br> </body> </html>
负责处理下载的servlet——download.java文件的内容如下:
package com.download.servlet; import java.io.fileinputstream; import java.io.ioexception; import java.io.inputstream; import javax.servlet.servletexception; import javax.servlet.servletoutputstream; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; /** * servlet implementation class download */ public class download extends httpservlet { private static final long serialversionuid = 1l; protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { //1.获取请求下载的文件名 string filename = request.getparameter("filename"); //2.获取文件的文件系统路径 string filepath = request.getservletcontext().getrealpath("resource/"+filename); //3.设置响应头,提示浏览器不要解析响应的文件数据,而是以附件(attachment)的形式解析,即下载功能 response.setcontenttype(this.getservletcontext().getmimetype(filename)); response.setheader("content-disposition", "attachment;filename="+filename); //4.读取文件的 输入流,以及响应的输出流,并将数据输出给客户端 inputstream in = new fileinputstream(filepath); servletoutputstream out = response.getoutputstream(); int len = 0; byte[] buf = new byte[1024]; while((len=in.read(buf))!=-1) { out.write(buf, 0, len); } in.close(); } protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { doget(request, response); } }
在浏览器地址栏中输入http://localhost:8080/downloadservlet/download.html。
以上这篇java web response提供文件下载功能的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。