JavaEE实现文件下载

2014-05-07  来源:本站原创  分类:Java  人气:2 

这篇文章主要介绍了JavaEE实现文件下载的方法,非常的实用,需要的朋友可以参考下

我们先来看一个最简单的文件下载的例子:

 package com.yyz.response;

 import java.io.FileInputStream;

 import java.io.IOException;

 import java.io.OutputStream;

 import javax.servlet.ServletException;

 import javax.servlet.http.HttpServlet;

 import javax.servlet.http.HttpServletRequest;

 import javax.servlet.http.HttpServletResponse;

 //文件下载

 public class ResponseDemo extends HttpServlet {

     public void doGet(HttpServletRequest request, HttpServletResponse response)

             throws ServletException, IOException {

         String realpath = this.getServletContext().getRealPath("/download/1.gif");

         String filename = realpath.substring(realpath.lastIndexOf("\\")+1);

         response.setHeader("content-disposition", "attachment;filename="+filename);

         //服务器通过这个头,告诉浏览器以下载方式打开数据

         FileInputStream in = new FileInputStream(realpath);

         int len = 0;

         byte buffer[]=new byte[1024];

         OutputStream out = response.getOutputStream();

         while((len = in.read(buffer))>0){

             out.write(buffer, 0, len);

             }

         in.close();

         //out不用close,response在销毁的时候服务器会自动关闭与response相关的流。

 }

     public void doPost(HttpServletRequest request, HttpServletResponse response)

             throws ServletException, IOException {

            doGet(request,response);

     }

 }

该段代码的功能是从服务器端下载图片1.png。目录结构用MyEclipse的package explorer显示如下:

JavaEE实现文件下载

让我们增加一点难度,我们要下载的文件是一个中文名字的文件。由于在http协议中头文件中的东西只能是ASCII字符,因而通过上述方式(直接将 String realpath = this.getServletContext().getRealPath("/download/1.gif");改为 String realpath = this.getServletContext().getRealPath("/download/图片.gif");)直接拿文件,

会出现乱码问题。附上测试结果:

JavaEE实现文件下载

要解决这个问题,要用到 URLEncoder类的encode方法:

复制代码 代码如下:

 package com.yyz.response;

 import java.io.FileInputStream;

 import java.io.IOException;

 import java.io.OutputStream;

 import java.net.URLEncoder;

 import javax.servlet.ServletException;

 import javax.servlet.http.HttpServlet;

 import javax.servlet.http.HttpServletRequest;

 import javax.servlet.http.HttpServletResponse;

 //中文文件下载时,中文文件名要经过URL编码。

 public class ResponseDemo extends HttpServlet {

     public void doGet(HttpServletRequest request, HttpServletResponse response)

             throws ServletException, IOException {

         String realpath = this.getServletContext().getRealPath("/download/图片.gif");

         String filename = realpath.substring(realpath.lastIndexOf("\\")+1);

         response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"UTF-8"));

        //本函数将字符串以 URL 编码

         FileInputStream in = new FileInputStream(realpath);

         int len = 0;

         byte buffer[]=new byte[1024];

         OutputStream out = response.getOutputStream();

         while((len = in.read(buffer))>0){

             out.write(buffer, 0, len);

             }

         in.close();

 }

     public void doPost(HttpServletRequest request, HttpServletResponse response)

             throws ServletException, IOException {

            doGet(request,response);

     }

 }

附上测试结果:

JavaEE实现文件下载

另外这里有一个小细节需要大家注意:

不能用FileReader代替FileInputStream。用FileReader会丢失数据,原因是这样的:FileReader是字符流,而图片,媒体文件等的数据都是以01的方式存储,用FileReader读的时候需要查阅一个编码表,如果未指定一种编码,则使用相应平台的默认编码。如在中国的电脑就会去查GB2312。当读到GB2312码表中不存在的编码时,会将该数据编码成'?',结束后数据就变成中文和'?'的混合。发到客户端后显示时再次查阅码表,将所有的'?'替换成'?'的编码,就会丢失数据。向这种细节只需要记住一点:字节流可以处理任意类型的数据,字符流只能处理字符数据。

相关文章
  • JavaEE实现文件下载 2014-05-07

    这篇文章主要介绍了JavaEE实现文件下载的方法,非常的实用,需要的朋友可以参考下 我们先来看一个最简单的文件下载的例子: package com.yyz.response; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServ

  • JavaEE of Service 2009-05-01

    1. Information "Java Transaction Design Strategies" InfoQ minibook, the best electronic documents, Java in a silly state of affairs must-read. "Expert One on one J2EE Development Without EJB English version" and the Spring reference ma

  • Resin to achieve JavaEE 6 specification (Laughter) 2010-03-29

    Resin to achieve JavaEE 6 specification Resin team is always focused on providing a lightweight, fast, reliable and easy to use application servers. We are proud of our tradition of lightweight, small size, independence and individuality, to treat a

  • The new Eclipse plug-in JSmart can quickly build the framework of the mainstream JavaEE 2010-03-29

    JSmart2 personal free version is worth trying a variety of functions Framework of the categories: 1, a key to generate the SSH framework 2, a key framework for generating SSH2 3, a key to generate the SSI framework, with iBatis map file generator (ju

  • javaEE learning pathways 2009-05-16

    javaEE learning pathways: Test first post

  • JAVAEE them in multiple browsers how to determine the user is not logged, if you have landed, is not allowed, it is in other places landing operation, and how. 2010-04-12

    JAVAEE them in multiple browsers how to determine the user is not logged, if you have landed, is not allowed, it is in other places landing operation, and how.

  • JavaEE good tool to improve development efficiency Javarebel ----- 2010-04-20

    We all know that the process of developing and debugging in JavaEE headache than most people like to amend the code to be readjusted each time the deployment, and even for some of Application Server must be restarted after running to see the effect o

  • JavaEE Enterprise Advisers 2010-06-30

    JavaEE Enterprise Advisor (J2ee Enterprise Consulting) duties (opening): Leadership - the bridge between business and technology Foresee - the insight to judge the key trends Develop strategies - simultaneously shaping the demand and Organizations -

  • javaEE using jquery to achieve a single page CURD 2010-07-10

    [Align = center] tools: eclipse 3 Database: mysql 5.0 Write a CURD use jquery plugin jquery-impromptu.2.7.min.js, A page list of additions and deletions to achieve a change investigation, no jumps, access to quickly project structure is as follows: t

  • JavaEE development of a list of common techniques 2010-10-15

    JavaEE development of a list of common techniques This is what I used to work (not the authority, may be used in the work of various different companies), this thought out, and hope to those who want to enter this industry are blind do not know what

  • eclipse for javaee web development environment configuration 2011-01-10

    1. Download to www.eclipse.org eclipse for javaee Version of the Eclipse, the highest version is far 3.6 2. Installation tomcat6.x, this is a more stable version 3. Installed in the Eclipse tomcat Plug-in, com.sysdeo.eclipse.tomcat_3.2.0, after the i

  • JavaEE application in Glassfish Case Study on the tuning 2011-09-14

    Java EE application performance problems for serious projects and products is a very important issue. Especially enterprise-class applications, and more concurrent users, data volume, complex business logic, taking up system resources, so performance

  • JavaEE参考示例 SpringSide 2008-09-14

    SpringSide 网站 : http://springside.io/ SpringSide是以Spring Framework为核心的,Pragmatic风格的JavaEE应用参考示例,是JavaEE世界中的主流技术选型,最佳实践的总结与演示. Quickstart: 一个迷你的Todo-List应用,演示CRUD Web+Restful API. Showcase: 五花八门的JavaEE技术大派对. SpringSide 由 @江南白衣 开发 授权协议: Apache 开发语言: Ja

  • 命令行文件下载工具 GNU Wget 2009-09-23

    GNU Wget 网站 : http://www.gnu.org/software/wget/ wget是一个从网络上自动下载文件的自由工具.它支持HTTP,HTTPS和FTP协议,可以使用HTTP代理. 所谓的自动下载是指,wget可以在用户退出系统的之后在后台执行.这意味这你可以登录系统,启动一个wget下载任务,然后退出系统,wget将在后台执行直到任务完成,相对于其它大部分浏览器在下载大量数据时需要用户一直的参与,这省去了极大的麻烦. wget 可以跟踪HTML页面上的链接依次下载来创建

  • JavaEE开源快速开发平台 G4Studio 2011-09-19

    G4Studio 网站 : http://www.oschina.net/action/project/go?id=18366&p=home G4Studio行业应用二次快速开发平台基于JavaEE技术体系,面向中小软件企业.以"标准功能可复用.通用模块可配置.行业需求快速开发.异构系统无缝集成"为目标,为中小软件开发团队提供强有力的一站式解决方案. 授权协议: GPLv3 开发语言: Java 查看源码» 操作系统: 跨平台

  • php实现文件下载简单示例(代码实现文件下载) 2013-11-01

    这篇文章主要介绍了php实现文件下载简单示例,需要的朋友可以参考下 public function downloads($name){ $name_tmp = explode("_",$name); $type = $name_tmp[0]; $file_time = explode(".",$name_tmp[3]); $file_time = $file_time[0]; $file_date = date("Y/md",$file_time

  • Ajax 生成流文件下载(实现代码) 2013-11-01

    使用Ajax生成流文件下载的功能,可以使用隐藏form的方式.需要的朋友可以参考下 // 绑定导出按钮 $("#btnExport").clickCheckLogin(function () { var form = $("<form>"); form.attr('style', 'display:none'); form.attr('target', ''); form.attr('method', 'post'); form.attr('action

  • JSP隐含对象response实现文件下载的两种方法 2013-11-04

    JSP隐含对象response实现文件下载的两种方式,二进制文件的下载与文本文件下载 一.JSP隐含对象response实现文件下载的介绍 (1)在JSP中实现文件下载最简单的方法是定义超链接指向目标资源,用户单击超链接后直接下载资源,但直接暴露资源的URL 也会带来一些负面的影响,例如容易被其它网站盗链,造成本地服务器下载负载过重. (2)另外一种下载文件的方法是使用文件输出流实现下载,首先通过response报头告知客户端浏览器,将接收到的信息另存 为一个文件,然后用输出流对象给客户端传输文

  • OBlog任意文件下载漏洞 2013-11-17

    OBlog任意文件下载漏洞 系统编号:BES2008053247 发布时间:2008-05-02 更新时间:2008-05-02 危害级别:★★★☆☆☆ 受影响版本: OBlog 4.60 描述: attachment.asp代码 Path = Trim(Request("path")) '获取用户提交的路径 FileID = Trim(Request("FileID")) If FileID ="" And Path = ""

  • VBS下载者(通过vbscript实现文件下载) 2013-11-17

    这篇文章主要介绍了通过vbscript实现文件下载功能的实现代码,主要是使用了ADODB.Stream,需要的朋友可以参考下 一.VBS下载者: Set Post = CreateObject("Msxml2.XMLHTTP") Set Shell = CreateObject("Wscript.Shell") Post.Open "GET","http://www.jbzj.com/muma.exe",0 Post.Send