文件下载

来源:互联网 发布:网店交易平台源码 编辑:程序博客网 时间:2024/05/16 15:08

       在web应用中实现文件下载的两种方式:

              ·超链接直接指向下载资源

              ·程序实现下载需设置两个响应头

·设置Context-type的值为:application/x-msdownload。Web服务器需要告诉留言器其输出的内容的类型不是普通的内容类型或者htnl文件,而是一个要存到本地的 下载文件

·web服务器希望留言器不直接处理响应的实体内容,而是由用户选择将相应的试题内容保存到一个文件中,这需要设置Content-Disposition报头。该报头制定了接收程序处理数据内容的方式,在http应用中只有attachment是标准方式,attachment表示要求用户干预。在attachment后面还可以指定filename参数,该参数是服务器建议浏览器将实体内容保存到文件中的文件名。在设置Content-dispositon之前一定要制定Content-Type

·因为要下载的文件可以是各种类型的文件,所以要将文件传送给客户端,其相应内容应该被当做二进制来处理,所以应该调用                               方法返回ServeltOutputStream 对象来向客户端写入文件内容。 

 

 

下载案例

       ListFileServlet.java:

读取某一个文件夹下的所有的文件,将其封装成一个file对象,多个file对象封装到一个集合对象中list,在将list对象存到一个作用于中才能传递给呈现所有的的资源的jsp页面中

 

packagecom.hbsi.servlet;

importjava.io.File;

import java.io.IOException;

import java.util.HashMap;

import java.util.Map;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public classListFileServlet extends HttpServlet {

 

//主体功能:将某一个文件夹下的所有文件获取到,然后存入到一个集合map 键uuidname---值file对象中,在集合存到作用于中

       public void doGet(HttpServletRequestrequest, HttpServletResponse response)

                     throws ServletException,IOException {

 

              //得到保存上传文件的文件夹

              Stringsavepath=this.getServletContext().getRealPath("WEB-INF/upload");

              Map map=new HashMap();

             

              listFiles(new File(savepath),map);

             

              request.setAttribute("map",map);

              request.getRequestDispatcher("/listfiles.jsp").forward(request,response);

       }

 

       //递归方法去遍历该文件夹下的所有文件以及子文件夹下的文件

       private void listFiles(File file,Mapmap){

             

              if(file.isFile()){//判断是否为文件

                     Stringuuidname=file.getName();

                     Stringrealname=uuidname.substring(uuidname.indexOf("_")+1);

                     map.put(uuidname,realname);

                    

             

              }else{

                     //若不是文件,而是文件夹

                     File[]files=file.listFiles();

                     for(File f:files){

                            listFiles(f,map);

                     }

              }

             

       }

      

       public void doPost(HttpServletRequestrequest, HttpServletResponse response)

                     throws ServletException,IOException {

              this.doGet(request, response);

       }

 

}

ListFile.jsp:

              呈现所有的下载资源,有超链接点击超链转到DownLoadServlet.java

              进行处理

 

<%@ page language="java" import="java.util.*"pageEncoding="utf-8"%>

<%@taglib uri="http://java.sun.com/jsp/jstl/core"prefix="c"%>

<%

String path =request.getContextPath();

String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

   

    <title>list files</title>

   

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control"content="no-cache">

    <meta http-equiv="expires"content="0">   

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

    <meta http-equiv="description" content="This is my page">

    <!--

    <link rel="stylesheet" type="text/css"href="styles.css">

    -->

 

  </head>

 

  <body>

   <h2>下载资源列表</h2>

   <c:forEach items="${map }"var="me">

        <c:url value="/servlet/DownloadSevlet" var="fileAddr">

           <c:param name="filename" value="${me.key}"></c:param>

        </c:url>

        文件名:${me.value}&nbsp;&nbsp;<a href="fileAddr">下载</a><br>

   </c:forEach>

  

  </body>

</html>

 

 

 

 

DownLoadServlet.java

              具体的处理

       packagecom.hbsi.servlet;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.io.PrintWriter;

 

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

 

public class DownloadSevlet extends HttpServlet{

 

       //具体文件下载

       publicvoid doGet(HttpServletRequest request, HttpServletResponse response)

                     throwsServletException, IOException {

 

              //确定保存位置,找到用户选定的文件

              Stringuuidname=request.getParameter("filename");

              uuidname=newString(uuidname.getBytes("ISO8859-1"),"utf-8");

             

              Stringralname=uuidname.substring(uuidname.indexOf("_")+1);

              StringsavePath=getFileAddr(ralname);

             

              Filef=new File(savePath+"\\"+uuidname);

              if(f.exists()){

             

                     response.setContentType("application/x-msdownload");

                     Stringstr="attachment;filename="+java.net.URLEncoder.encode(ralname,"utf-8");

                     response.setHeader("Content-Disposition",str);

             

                     //创建一个输入流对象和指定的文件相关联

                     FileInputStreamin=new FileInputStream(f);

                     //response对象获取输出流

                     OutputStreamout=response.getOutputStream();

                     //从输入流对象中读取数据写入到输出流对象中

                     byte[]buff=new byte[1024];

                     intlen=0;

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

                            out.write(buff,0,len);

                     }

              }else{

                     request.setAttribute("message","下载资源不存在!");

                     request.getRequestDispatcher("/message.jsp").forward(request,response);

              }

       }

      

       privateString getFileAddr(String filename){

              intdir1=filename.hashCode() & 0x0f;

              intdir2=filename.hashCode() >>4 & 0x0f;

              StringsavePath=this.getServletContext().getRealPath("WEB-INF/upload")+"\\"+ dir1 + "\\" + dir2;

              returnsavePath;

       }

      

       publicvoid doPost(HttpServletRequest request, HttpServletResponse response)

                     throwsServletException, IOException {

 

              this.doGet(request,response);

       }

 

}

 

原创粉丝点击