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. Codeforces Round #371 (Div. 2) D. Searching Rectangles 交互题 二分

    D. Searching Rectangles 题目连接: http://codeforces.com/contest/714/problem/D Description Filya just lea ...

  2. Codeforces Round #368 (Div. 2) A. Brain's Photos 水题

    A. Brain's Photos 题目连接: http://www.codeforces.com/contest/707/problem/A Description Small, but very ...

  3. 手机浏览器跳转APP

    背景 对于APP来说,回流分享页是最好的最便宜的也是最病毒式的拉新方式.让新用户去下载APP是重要的.对老用户来说,可以直接调起APP也是提升用户体验和让用户有侵入式体验的重要手段.所以我们一起来看看 ...

  4. CRC32 of Ether FCS with STM32

    Everyone knows that STM32F1xx, STM32F2xx, STM32F4xx have a hardware unit with a polynomial CRC32 0x0 ...

  5. LOG EXPLORER ApexSQL Log

    http://www.minisoft.cn/ https://www.apexsql.com/sql_tools_log.aspx

  6. systemtap跟踪C

    1.[root@localhost ~]# rpm -qi  glibcName        : glibc                        Relocations: (not rel ...

  7. mysql主从同步失败Last_IO_Error: Got fatal error 1236 from master解决方法

    mysql教程主从同步失败Last_IO_Error: Got fatal error 1236 from master解决方法 遇到这样的错误如:“Last_IO_Error: Got fatal ...

  8. 线程池框架executor

    Eexecutor作为灵活且强大的异步执行框架,其支持多种不同类型的任务执行策略,提供了一种标准的方法将任务的提交过程和执行过程解耦开发,基于生产者-消费者模式,其提交任务的线程相当于生产者,执行任务 ...

  9. Win7 ArcGIS 10.5 安装错误 A service pack is required on this operatiing system

    前段时间有朋友反馈在Win7专业版下安装ArcGIS 10.5, 无法安装,弹出错误: A service pack is required on this operatiing system,如图: ...

  10. blob转base64位 base64位转blob

    //**dataURL to blob** function dataURLtoBlob(dataurl) { var arr = dataurl.split(','), mime = arr[0]. ...