java使用Servlet进行文件下载
来源:互联网 发布:工地记工软件 编辑:程序博客网 时间:2024/06/05 02:25
1. 概述
java通过servlet的方式进行文件下载,response获取输出流将文件传到浏览器,在浏览器中便可进行下载。我是获取的HDFS上的文件流,不管文件在哪里,本质上都是一样的。废话不多说,直接上代码吧。
2. java代码
FileDownLoadServlet.java
package servlet;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import util.FileUtil;/** * Servlet 文件下载 */@WebServlet("/FileDownLoadServlet")public class FileDownLoadServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public FileDownLoadServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); System.out.println("文件下载"); // 文件路径 String FilePath = new String(req.getParameter("FilePath").getBytes("ISO8859-1"),"UTF-8"); // 下载文件的文件名 String localFileName = new String(req.getParameter("localFileName").getBytes("ISO8859-1"),"UTF-8"); String[] Paths = FilePath.split(","); if(Paths.length == 1) {// ==1, 表示只有一个文件下载 oneFile(req, resp); } else if(Paths.length > 1) { // 压缩下载 System.out.println("多个文件"); try { MoreFile(req, resp); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * 单个文件下载 * @param req * @param resp * @throws UnsupportedEncodingException */ public void oneFile(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException { String HDFSPath = new String(req.getParameter("FilePath").getBytes("ISO8859-1"),"UTF-8"); String localFileName = new String(req.getParameter("localFileName").getBytes("ISO8859-1"),"UTF-8"); try { String FilePath = new String(req.getParameter("FilePath").getBytes("ISO8859-1"),"UTF-8"); InputStream in = FileUtil.getFileInputStream(FilePath); // 输出流 OutputStream out = resp.getOutputStream(); //设置文件MIME类型 resp.setContentType(getMimeType(localFileName)); // 设置Content-Disposition ,filename后面进行了编码的转换,如果编码不对, // 在浏览器上下载的时候,如果是中文的文件名,可能会显示不对 resp.setHeader("Content-Disposition", "attachment;filename="+new String(localFileName.getBytes(), "ISO-8859-1")); // 写文件 int b = 0; while((b = in.read()) != -1) { out.write(b); } in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 多个文件下载 * 多个文件采用的是将文件先放在一个临时目录下,等待所有文件都压缩完成后,将压缩包传到浏览器中进行下载 * @throws Exception */ public void MoreFile(HttpServletRequest req, HttpServletResponse resp) throws Exception { System.out.println("多个文件下载"); // 待下载文件 String HDFSPath = new String(req.getParameter("FilePath").getBytes("ISO8859-1"),"UTF-8"); // 下载后的文件 String localFileName = new String(req.getParameter("localFileName").getBytes("ISO8859-1"),"UTF-8"); // 压缩包名称 String zipName = new String(req.getParameter("zipName").getBytes("ISO8859-1"),"UTF-8"); //设置文件MIME类型 // resp.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); //设置Content-Disposition resp.setContentType(getMimeType(zipName)); resp.setHeader("Content-Disposition", "attachment;filename="+new String(zipName.getBytes(), "ISO-8859-1")); String[] Paths = HDFSPath.split(","); String[] localFileNames = localFileName.split(","); // 存放压缩文件的临时目录 File tmp = new File("E:zipFile"); if(!tmp.exists()) { tmp.mkdirs(); } // 随机生成一串字符串作为文件名 String fileName = autoid20() + ".zip"; File zipFile = new File("E:zipFile\\" + fileName + ".zip"); // 压缩文件 FileUtil.zipFiles(Paths, localFileNames, zipFile); try { InputStream in = new FileInputStream(zipFile); OutputStream out = resp.getOutputStream(); int read; byte[] b = new byte[1024 * 4]; while((read = in.read(b)) > 0) { out.write(b, 0, b.length); } in.close(); out.close(); // 下载完毕后删除临时文件 zipFile.delete(); } catch (Exception e) { e.printStackTrace(); } } /** * 根据文件名返回MIME类型 * 只是简单的根据文件后缀名对几个常用的文件类型进行了判断然后返回MIME类型 * 如果想做更加准确的,请自行研究哦 * @param FileName * @return */ public String getMimeType(String FileName) { System.out.println("filename" + FileName); int end = FileName.lastIndexOf("."); String last = FileName.substring(end, FileName.length()); if(last.equals(".docx")) { return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; } if(last.equals(".doc")) { return "application/msword"; } if(last.equals(".pdf")) { return "application/pdf"; } if(last.equals(".zip")) { return "application/x-zip-compressed"; } return ""; } public String autoid20() { int defaultVal = 100; defaultVal = (defaultVal < 500) ? defaultVal : 100; String str = String.valueOf(System.currentTimeMillis()) + (defaultVal++); return Long.toString(Long.decode(str).longValue(), 36); }}
FileUtil.java
package util;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;public class FileUtil { /** * 获得文件输入流 * @param filePath * @throws FileNotFoundException */ public static InputStream getFileInputStream(String filePath) throws FileNotFoundException { File file = new File(filePath); FileInputStream in = new FileInputStream(file); return in; } /** * 功能:压缩多个文件成一个zip文件 * @param srcfile:源文件列表 * @param zipfile:压缩后的文件 * @throws Exception */ public static void zipFiles(String[] srcfile,String[] localName,File zipfile) throws Exception{ byte[] buf=new byte[1024]; //ZipOutputStream类:完成文件或文件夹的压缩 ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipfile)); InputStream in = null; for(int i=0;i<srcfile.length;i++){ try { in = getFileInputStream(srcfile[i]); out.putNextEntry(new ZipEntry(localName[i])); int len; while((len=in.read(buf))>0){ out.write(buf,0,len); } }catch (Exception e) { e.printStackTrace(); if(in != null) { in.close(); in = null; } continue; } } out.close(); System.out.println("压缩完成."); }}
3. 浏览器下载
####单个文件localhost:8080/FileDownload/FileDownLoadServlet?FilePath=C:\Users\echo\Desktop\222.docx&localFileName=本地文件.docx####多个文件,我使用的,进行文件的分隔localhost:8080/FileDownload/FileDownLoadServlet?FilePath=C:\Users\echo\Desktop\222.docx,C:\Users\echo\Desktop\223.docx&localFileName=本地文件.docx,a.docx&zipName=压缩.zip
4. 结果
单个文件下载
多个文件下载
阅读全文
0 0
- java使用Servlet进行文件下载
- java Servlet 文件下载
- Servlet中进行文件下载的写法
- servlet进行文件的上传和下载
- java文件的上传与下载原理(使用Servlet)
- 通过Java Servlet进行文件下载时的IE缓存问题
- Java使用SmartUploadServlet进行文件的上传与下载
- 使用数据流进行文件下载
- 使用DownloadManager进行文件下载
- 使用Struts2进行文件下载
- 使用servlet进行多文件的上传
- 使用Servlet实现动态文件下载
- servlet使用迅雷下载excel文件乱码
- 使用Servlet实现页面下载文件
- javaweb-使用servlet实现文件下载
- 使用Servlet实现下载文件的功能
- 使用Servlet实现下载文件的功能
- 使用Servlet实现下载文件的功能
- Leetcode:Two Sum
- 160个练手CrackMe-008
- 实验一(模板类操作)
- 【greenDAO3】 项目搭建与增删改查操作
- 13.MariaDB笔记——cmake使用介绍八支持面板
- java使用Servlet进行文件下载
- 欢迎使用CSDN-markdown编辑器
- Python3.6 str内置方法
- 走穿java23种设计模式-6代理模式
- 安全开发之IP地址伪造
- Oracle连接查询,彻底搞懂外连接(左外连接&右外连接)
- 第5周项目1 建立顺序栈算法库
- java AWT ImageIO(输入/输出位图)
- C语言实验——三个整数和、积与平均值