http://blog.csdn.net/longshengguoji/article/details/39433307

需求:实现一个具有文件下载功能的网页,主要下载压缩包和图片

两种实现方法:

一:通过超链接实现下载

在HTML网页中,通过超链接链接到要下载的文件的地址
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Insert title here</title>
  6. </head>
  7. <body>
  8. <h1>通过链接下载文件</h1>
  9. <a href="/day06/download/cors.zip">压缩包</a>
  10. <a href="/day06/download/1.png">图片</a>
  11. </body>
  12. </html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>通过链接下载文件</h1>
<a href="/day06/download/cors.zip">压缩包</a>
<a href="/day06/download/1.png">图片</a>
</body>
</html>

其中day06/download是文档路径,本实例的程序结构如下:

程序运行后,可以通过单击需要下载文档实现下载
但是这里会出现一个问题,就是单击下载压缩包的时候会弹出下载页面,但是下载图片的时候浏览器就直接打开了图片,没有下载。
    这是因为通过超链接下载文件时,如果浏览器可以识别该文件格式,浏览器就会直接打开。只有浏览器不能识别该文件格式的时候,才会实现下载。因此利用第二种方法实现下载功能。

二:通过Servlet程序实现下载

    通过Servlet下载文件的原理是通过servlet读取目标程序,将资源返回客户端。
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Insert title here</title>
  6. </head>
  7. <body>
  8. <h1>通过链接下载文件</h1>
  9. <a href="/day06/download/cors.zip">压缩包</a>
  10. <a href="/day06/download/1.png">图片</a>
  11. <h1>通过servlet程序下载文件</h1>
  12. <a href="/day06/ServletDownload?filename=cors.zip">压缩包</a>
  13. <a href="/day06/ServletDownload?filename=1.png">图片</a>
  14. </body>
  15. </html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>通过链接下载文件</h1>
<a href="/day06/download/cors.zip">压缩包</a>
<a href="/day06/download/1.png">图片</a>
<h1>通过servlet程序下载文件</h1>
<a href="/day06/ServletDownload?filename=cors.zip">压缩包</a>
<a href="/day06/ServletDownload?filename=1.png">图片</a>
</body>
</html>

其中,/day06/ServletDownload 是servlet程序的映射路径

然后新建一个servlet,名称为ServletDownload,URL映射为/ServletDownload
添加代码如下:
  1. package com.lsgjzhuwei.servlet.response;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import javax.servlet.ServletException;
  8. import javax.servlet.annotation.WebServlet;
  9. import javax.servlet.http.HttpServlet;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. /**
  13. * Servlet implementation class ServletDownload
  14. */
  15. @WebServlet(asyncSupported = true, urlPatterns = { "/ServletDownload" })
  16. public class ServletDownload extends HttpServlet {
  17. private static final long serialVersionUID = 1L;
  18. /**
  19. * @see HttpServlet#HttpServlet()
  20. */
  21. public ServletDownload() {
  22. super();
  23. // TODO Auto-generated constructor stub
  24. }
  25. /**
  26. * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  27. */
  28. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  29. // TODO Auto-generated method stub
  30. //获得请求文件名
  31. String filename = request.getParameter("filename");
  32. System.out.println(filename);
  33. //设置文件MIME类型
  34. response.setContentType(getServletContext().getMimeType(filename));
  35. //设置Content-Disposition
  36. response.setHeader("Content-Disposition", "attachment;filename="+filename);
  37. //读取目标文件,通过response将目标文件写到客户端
  38. //获取目标文件的绝对路径
  39. String fullFileName = getServletContext().getRealPath("/download/" + filename);
  40. //System.out.println(fullFileName);
  41. //读取文件
  42. InputStream in = new FileInputStream(fullFileName);
  43. OutputStream out = response.getOutputStream();
  44. //写文件
  45. int b;
  46. while((b=in.read())!= -1)
  47. {
  48. out.write(b);
  49. }
  50. in.close();
  51. out.close();
  52. }
  53. /**
  54. * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  55. */
  56. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  57. // TODO Auto-generated method stub
  58. }
  59. }
package com.lsgjzhuwei.servlet.response;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class ServletDownload
*/
@WebServlet(asyncSupported = true, urlPatterns = { "/ServletDownload" })
public class ServletDownload extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public ServletDownload() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
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();
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
} }

重启tomcat服务器,即可实现对压缩包和对图片的下载。

java web文件下载功能实现 (转)的更多相关文章

  1. 【Servlet】java web 文件下载功能实现

    需求:实现一个具有文件下载功能的网页,主要下载压缩包和图片 两种实现方法: 一:通过超链接实现下载 在HTML网页中,通过超链接链接到要下载的文件的地址 <!DOCTYPE html> & ...

  2. Java Web文件下载

    Web文件下载有两种.一种是文件在站点文件夹下.在浏览器中直接输入文件路径就可以下载.如http://www.xxx.com/file.zip.第二种是文件不在站点文件夹下或者文件是动态生成的(导出报 ...

  3. JAVA WEB ------ 文件下载及导出数据到office Execl表格

    文件下载需要五步: 1.设置文件ContentType类型 // 设置文件ContentType类型,这样设置,会自动判断下载文件类型 response.setContentType("mu ...

  4. Java web 文件下载

    /** * 下载文件 * @param msg */ public boolean printOutFile(String fileFullName,String fileName) { if (fi ...

  5. java io 文件下载功能

    一. @RequestMapping(value = "/download/{filename}") public void downloadFile(HttpServletReq ...

  6. Java Web(一) Servlet详解!!

    这篇文章到上一篇,距离的有点遥远呀,隔了大概有两个月把,中间在家过了个年,哈哈~ 现在重新开始拾起,最近在看一本个人觉得很棒的书,<Java Web 整合开发王者归来>,现在写的这一系列基 ...

  7. (转)Java Web(一) Servlet详解!!

    https://www.cnblogs.com/whgk/p/6399262.html 这篇文章到上一篇,距离的有点遥远呀,隔了大概有两个月把,中间在家过了个年,哈哈~ 现在重新开始拾起,最近在看一本 ...

  8. 重拾Java Web应用的基础体系结构

    目录 一.背景 二.Web应用 2.1 HTML 2.2 HTTP 2.3 URL 2.4 Servlet 2.4.1 编写第一个Servlet程序 2.5 JSP 2.6 容器 2.7 URL映射到 ...

  9. JAVA文件下载功能问题解决日志

    今天给报告系统做了个下载功能,遇到了挺多问题,通过查资料一一解决了. 1.首先遇到的问题是:java后台的输出流输出之后,没有任何报错,浏览器端不弹出保存文件的对话框,原本是ajax请求到后台的con ...

随机推荐

  1. CentOS 7搭建KVM在线管理面板WebVirtMgr

    系统版本:CentOS 7.4 WebVirtMgr版本:master分支的20180720版本,下载链接(链接:https://pan.baidu.com/s/1kl060hPHDGbwJUR_iM ...

  2. LPCScrypt, DFUSec : USB FLASH download, programming, and security tool, LPC-Link 2 Configuration tool, Firmware Programming

    What does this tool do? The LPC18xx/43xx DFUSec utility is a Windows PC tool that provides support f ...

  3. WinForm多线程实现HTTP网络检测工具

    一.背景描述与课程介绍 明人不说暗话,跟着阿笨一起玩WinForm.本次分享课程属于<C#高级编程实战技能开发宝典课程系列>中的一部分,阿笨后续会计划将实际项目中的一些比较实用的关于C#高 ...

  4. Snmp学习总结(三)——Win7安装和配置SNMP

    一.安装SNMP Win7操作系统默认情况下是不安装SNMP服务的,今天讲解一下在Win7操作系统下安装SNMP,具体安装步骤如下: WIN7操作系统下安装SNMP的步骤如下: 开始安装SNMP

  5. libxml/HTMLparser.h file

    在导入asihttprequest包时出问题导入了libxml2.dylib,但是却提示libxml/HTMLparser.h file not found,那是因为你的开发环境默认的路径无法找到这个 ...

  6. JavaScript 检查IP

    //---------------------------------------------------------- // 功能:检查IP // 参数: // strpart ip地址 // 返回 ...

  7. 泛泰A860(高通8064 cpu 1080p) 刷4.4专用中文recovery TWRP2.7.1.2版(三版通刷)

    欢迎关注泛泰非盈利专业第三方开发团队 VegaDevTeam  (本team 由 syhost suky zhaochengw(z大) xuefy(大星星) tenfar(R大师) loogeo cr ...

  8. Library drmframework_jni not found

    http://piotrbuda.eu/2012/06/trying-to-solve-error-491-in-play-store-on-android-emulator.html http:// ...

  9. Java并发编程的艺术(九)——批量获取多条线程的执行结果

    当向线程池提交callable任务后,我们可能需要一次性获取所有返回结果,有三种处理方法. 方法一:自己维护返回结果 // 创建一个线程池 ExecutorService executorServic ...

  10. Asp.Net Core获取请求信息/获取请求地址

     一.Asp.Net Core 2.0版本中目前HttpRequest是个抽象类 在控制器或视图上下文中获取到的 Request对象,是 DefaultHttpRequest的实例. 定义 如图 : ...