我是靠谱客的博主 可靠宝马,这篇文章主要介绍使用Servlet实现下载文件的功能,现在分享给大家,希望可以做个参考。

在前台有一个下载链接,比如

 

复制代码
1
<a href="DownLoadServlet">下载</a> <br/>

 


使用Servlet实现下载:

 

 

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DownLoadServlet extends HttpServlet { public DownLoadServlet() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //处理请求 //读取要下载的文件 File f = new File("E:/好久不见.mp3"); if(f.exists()){ FileInputStream fis = new FileInputStream(f); String filename=URLEncoder.encode(f.getName(),"utf-8"); //解决中文文件名下载后乱码的问题 byte[] b = new byte[fis.available()]; fis.read(b); response.setCharacterEncoding("utf-8"); response.setHeader("Content-Disposition","attachment; filename="+filename+""); //获取响应报文输出流对象 ServletOutputStream out =response.getOutputStream(); //输出 out.write(b); out.flush(); out.close(); } } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }

 

 

 

配置文件注意路径。。。

 

 

本文来源于 :http://www.cnblogs.com/android-html5/archive/2012/03/16/2534082.html

转载于:https://www.cnblogs.com/ys-wuhan/p/5772730.html

最后

以上就是可靠宝马最近收集整理的关于使用Servlet实现下载文件的功能的全部内容,更多相关使用Servlet实现下载文件内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(56)

评论列表共有 0 条评论

立即
投稿
返回
顶部