项目中用到的下载文件功能代码
来源:互联网 发布:淘宝东西怎么上架 编辑:程序博客网 时间:2024/05/16 14:17
一、整体思路
文件下载
文件下载功能是web开发中经常使用到的功能,使用HttpServletResponse对象就可以实现文件的下载
文件下载功能的实现思路:
1.获取要下载的文件的绝对路径
2.获取要下载的文件名
3.设置content-disposition响应头控制浏览器以下载的形式打开文件
4.获取要下载的文件输入流
5.创建数据缓冲区
6.通过response对象获取OutputStream流
7.将FileInputStream流写入到buffer缓冲区
8.使用OutputStream将缓冲区的数据输出到客户端浏览器
二、servlet实现
<span style="font-size:14px;">package com.soft.controller;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * * @author lim.jong.uk *文件下载servlet */public class DownFileServlet extends HttpServlet {private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {downloadFileByOutputStream(response);}/** * 下载文件,通过OutputStream流 * @param response * @throws Exception */private void downloadFileByOutputStream(HttpServletResponse response)throws FileNotFoundException, IOException {//1、获取要下载的文件的绝对路径String realPath = this.getServletContext().getRealPath("/download/1.png");System.out.println("文件的绝对路径:" + realPath);//2、获取要下载的文件名String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);//截取的时候开始的位置为0,所以要加1System.out.println("截取没有加1:" + realPath.substring(realPath.lastIndexOf("\\")));//截取没有加1:\1.pngSystem.out.println("获取要下载的文件名:" + fileName);//1.png//3、设置content-disposition响应头控制浏览器以下载的形式打开文件response.setHeader("content-disposition", "attachment;filename="+fileName);//4、获取要下载的文件输入流InputStream in = new FileInputStream(realPath);int len = 0;//5、创建数据缓冲区byte[] buffer = new byte[1024];//6、通过response对象获取OutputStream流OutputStream out = response.getOutputStream();//7、将FilInputStream流写入到buffer缓冲区while((len = in.read(buffer) )> 0){out.write(buffer, 0, len);}//关闭流in.close();out.close();}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request,response);}}</span>
<span style="font-size:14px;font-weight: normal;">package com.soft.controller;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.io.PrintWriter;import java.net.URLEncoder;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * 使用Response实现中文文件下载 * 下载含有中文名称路径的文件 * 说明:下载中文文件时,需要注意的地方就是中文文件名要使用URLEncoder.encode * 方法进行编码(URLEncoder.encode(fileName, "字符编码")),否则会出现文件名乱码。 * @author lim.jong.uk * 所以使用PrintWriter流处理字节数据,会导致数据丢失,这一点千万要注意,因此在编写下载文件功能时, * 要使用OutputStream流,避免使用PrintWriter流,因为OutputStream流是字节流,可以处理任意类型的数据, * 而PrintWriter流是字符流,只能处理字符数据,如果用字符流处理字节数据,会导致数据丢失。 * */public class DownChineseFileServlet extends HttpServlet {private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {downloadChineseFileByOutputStream(response);}/** * 下载中文文件,中文文件下载时,文件名要经过URL编码,否则会出现文件名乱码 * @param response * @throws FileNotFoundException * @throws IOException注意,抛出的异常不可以比调用的方法的异常大(也就是不能是抛出调用方法的异常的父类异常) */private void downloadChineseFileByOutputStream(HttpServletResponse response)throws FileNotFoundException,IOException{//获取要下载的文件的绝对路径String realPath = this.getServletContext().getRealPath("/download/你好.png");//获取要下载的文件名String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);System.out.println("获取要下载的文件名:" + fileName);//设置content-disposition响应头控制浏览器以下载的形式打开文件,中文文件名要使用URLEncoder.encode方法进行编码,否则会出现文件名乱码response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(fileName, "UTF-8"));//获取文件输入流FileReader in = new FileReader(realPath);int len = 0;char[] buffer = new char[1024];//构建一个字符缓冲区PrintWriter out = response.getWriter();while((len = in.read(buffer)) > 0){out.write(buffer, 0, len);}in.close();out.close();}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request,response);}}</span>
三、springmvc实现
<span style="font-size:14px;">import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.OutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;/** * 文件下载 * @author * */@Controller@RequestMapping("/down/*")public class FileDownloadController {private BufferedInputStream buff;@RequestMapping("downLoad")public ModelAndView downLoad( HttpServletRequest request, HttpServletResponse response){ ModelAndView mav = new ModelAndView("返回的页面"); try { response.setContentType("application/octet-stream"); String filename = null;filename = new String(request.getParameter("FILE_NAME").getBytes("iso-8859-1"),"utf-8");String FL_MASK_NM = request.getParameter("FL_MASK_NM");if(!StringUtils.hasText(FL_MASK_NM)){FL_MASK_NM = filename;} //创建file对象 File file=new File(JProperties.getString(JFileConsts.DEFAULT_FILE_UPLOAD_PATH_KEY)+"/"+FL_MASK_NM); //设置response的编码方式 response.setContentType("application/x-msdownload"); //写明要下载的文件的大小 response.setContentLength((int)file.length()); //设置附加文件名 response.setHeader("Content-Disposition","attachment;filename="+filename); //解决中文乱码 response.setHeader("Content-Disposition","attachment;filename="+new String(filename.getBytes("utf-8"),"iso-8859-1")); //读出文件到i/o流 FileInputStream fis=new FileInputStream(file); buff = new BufferedInputStream(fis); byte [] b=new byte[1024]; long k=0;//该值用于计算当前实际下载了多少字节 //从response对象中得到输出流,准备下载 OutputStream myout=response.getOutputStream(); //开始循环下载 while(k<file.length()){ int j=buff.read(b,0,1024); k+=j; //将b中的数据写到客户端的内存 myout.write(b,0,j); } //将写入到客户端的内存的数据,刷新到磁盘 myout.flush(); } catch (Exception e) {e.printStackTrace();} return mav;}}</span>
说明:该文章servlet下载为借鉴别人的。
0 0
- 项目中用到的下载文件功能代码
- 项目中用到的Android代码整理
- 几个项目中用到的代码片段
- 项目实际运用中用到spring的什么功能?
- 项目中用到的
- 在项目中用到的一些JS代码
- JAVA Web项目中用到Redis的代码调试
- 代码总结:IOS正则表达式(项目中用到的)
- 项目中用到的开源库
- 项目中用到的工具
- 项目中用到的css
- 文件下载功能代码示例
- 跳转中用到的定时功能
- 应用中用到拍照、摄像功能的
- 最近项目中用到的图片上传前预览功能,兼容IE6-9,FF
- 项目中用到的2个工具类代码:FTP与SendMail
- 项目中用到的2个工具类代码:FTP与SendMail
- 项目管理中用到的图释
- json_decode解码失败.
- 检测arp攻击
- Android Volley完全解析(三),定制自己的Request
- (1.2.1.1)单链表的逆转倒置、验环、倒数第M个节点和相交
- hdu 3068 最长回文 (manacher模板)
- 项目中用到的下载文件功能代码
- PE文件详解:资源结构体
- 后缀数组_模板
- ab命令
- Cron 表达式
- dd备份命令
- iOS 压缩和解压
- ulimit命令
- 插入排序