您的位置:首页 > 其它

文件的下载详解及案例解析

2011-11-25 14:03 141 查看
文件的下载详解及案例解析

一. Web应用中实现文件下载的两种方式

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

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

• 设置Content-Type 的值为:application/x-msdownload。Web 服务器需要告诉浏览器其所输出的内容的类型不是普通的文本文件或 HTML 文件,而是一个要保存到本地的下载文件

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

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

三. 遍历上传目录下的所有文件显示给用户,并允许用户完成下载。

四. (读取某一个文件夹下的所有的文件,存到集合里面List,再存到request作用域范围中)ListFileServelt—(将所有的文件列表显示)Listfiles.jsp-----DownloaServlet.java

五. 案例详解:

第一步: 将某一个文件夹下的文件获取到存入到一个集合里面

package com.hbsi.servlet;

import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

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 class ListFileServlet extends HttpServlet {

//将某一个文件夹下的文件获取到存入到一个集合里面Map key=uuidname value=realname

public voiddoGet(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException {

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

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

Mapmap=new HashMap();

listFile(newFile(savePath),map);

request.setAttribute("map",map);

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

}

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

private voidlistFile(File file, Map map ){

//File []files=file.listFiles()

//File[0]File[1]

if(file.isFile()){

//如果是文件的话

Stringuuidname=file.getName();

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

map.put(uuidname,realname);

}else{

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

File[] files=file.listFiles();

for(Filef:files){

listFile(f,map);

}

}

}

public voiddoPost(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException {

doGet(request,response);

}

}

第二步:<%@ 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//DTDHTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'listfiles.jsp' starting page</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">
<%--url编码 --%>
<c:url value="/servlet/DownloadServlet"var="fileAddr">
<c:param name="filename"value="${me.key}"></c:param>

</c:url>
文件名:${me.value}
<a href="${fileAddr}">下载</a>

<br>

</c:forEach>

</body>
</html>
第三步:

package com.hbsi.servlet;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {

//具体文件的下载

public voiddoGet(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException {

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

//解决乱码

//request.setCharacterEncoding("utf-8");

Stringuuidname=request.getParameter("filename");

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

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

StringsavePath=getFileAddr(realname);

File f=newFile(savePath+"\\"+uuidname);

if(f.exists()){

//设置消息头

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

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

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

//首先要创建一个输入流对象和制定的文件象像关联

FileInputStreamin=new FileInputStream(savePath+"\\"+uuidname);

//request对象中获取输出流对象

OutputStreamout=response.getOutputStream();

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

byte[]buff=new byte[1024];

int len;

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

out.write(buff,0,len);

}

}

else{

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

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

}

}

private StringgetFileAddr(String filename){

intdir1=filename.hashCode() & 0x0f;

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

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

returnsavePath;

}

/**

* The doPost method of the servlet. <br>

*

* This method is called when a form has itstag value method equals to post.

*

* @param request the request send by theclient to the server

* @param response the response send by theserver to the client

* @throws ServletException if an error occurred

* @throws IOException if an error occurred

*/

public voiddoPost(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException {

doGet(request,response);

}

}

package com.hbsi.servlet;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {

//具体文件的下载

public voiddoGet(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException {

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

//解决乱码

//request.setCharacterEncoding("utf-8");

Stringuuidname=request.getParameter("filename");

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

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

StringsavePath=getFileAddr(realname);

File f=newFile(savePath+"\\"+uuidname);

if(f.exists()){

//设置消息头

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

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

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

//首先要创建一个输入流对象和制定的文件象像关联

FileInputStreamin=new FileInputStream(savePath+"\\"+uuidname);

//request对象中获取输出流对象

OutputStreamout=response.getOutputStream();

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

byte[]buff=new byte[1024];

int len;

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

out.write(buff,0,len);

}

}

else{

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

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

}

}

private StringgetFileAddr(String filename){

intdir1=filename.hashCode() & 0x0f;

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

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

returnsavePath;

}

/**

* The doPost method of the servlet. <br>

*

* This method is called when a form has itstag value method equals to post.

*

* @param request the request send by theclient to the server

* @param response the response send by theserver to the client

* @throws ServletException if an erroroccurred

* @throws IOException if an error occurred

*/

public voiddoPost(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException {

doGet(request,response);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: