<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>downservlet</servlet-name>
<servlet-class>com.vacational.servlet.downservlet</servlet-class>
<init-param>
<param-name>fileRoot</param-name>
<param-value>d:/temp</param-value>
</init-param>
<init-param>
<param-name>contentType</param-name>
<param-value>application/x-msdownload</param-value>
</init-param>
<init-param>
<param-name>enc</param-name>
<param-value>utf-8</param-value>
</init-param>
</servlet>
</servlet-mapping>
<servlet-mapping>
<servlet-name>downservlet</servlet-name>
<url-pattern>/down</url-pattern>
</servlet-mapping>
public class downservlet extends HttpServlet {
private String contentType = "application/x-msdownload";
private String enc = "utf-8";
private String fileRoot = "";
/**
* 初始化contentType,enc,fileRoot
*/
public void init(ServletConfig config) throws ServletException {
String tempStr = config.getInitParameter("contentType");
if (tempStr != null && !tempStr.equals("")) {
contentType = tempStr;
}
tempStr = config.getInitParameter("enc");
if (tempStr != null && !tempStr.equals("")) {
enc = tempStr;
}
tempStr = config.getInitParameter("fileRoot");
if (tempStr != null && !tempStr.equals("")) {
fileRoot = tempStr;
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filepath = request.getParameter("filepath");
String fullFilePath = fileRoot + filepath;
/*讀取文件*/
File file = new File(fullFilePath);
/*如果文件存在*/
if (file.exists()) {
String filename = URLEncoder.encode(file.getName(), enc);
response.reset();
response.setContentType(contentType);
response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
int fileLength = (int) file.length();
response.setContentLength(fileLength);
/*如果文件長(zhǎng)度大于0*/
if (fileLength != 0) {
/*創(chuàng)建輸入流*/
InputStream inStream = new FileInputStream(file);
byte[] buf = new byte[4096];
/*創(chuàng)建輸出流*/
ServletOutputStream servletOS = response.getOutputStream();
int readLength;
while (((readLength = inStream.read(buf)) != -1)) {
servletOS.write(buf, 0, readLength);
}
inStream.close();
servletOS.flush();
servletOS.close();
}
}
}
}
Jsp頁(yè)面:
<a href=”down?filepath=/aa.doc”>下載</a>
下面還有一個(gè)例子:
--------------------------------------------------------download.jsp-------------------------------------------------------
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html lang="true">
<head>
<html:base />
<title>download.jsp</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>
<form action="downloadAction">
<html:submit>DownLoad</html:submit>
</form>
</body>
</html:html>
-------------------------------------------------DownloadAction.java--------------------------------------------------
package com.sh.struts.action;
import java.io.File;
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;
public class DownloadAction extends HttpServlet {
private static final long serialVersionUID = 6173045657186686318L;
public DownloadAction() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/x-download");
String url = "E://JavaProject/ECA/WebRoot/client/TopicVault_Client_V_1_8_4.exe";
String fileName = "TopicVault_Client_V_1_8_4.exe";
fileName = URLEncoder.encode(fileName, "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename="+ fileName);
out(url, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public void init() throws ServletException {
}
private void out(String url, HttpServletResponse response) {
int i = 0;
byte[] b = new byte[1024];
File file = new File(url);
FileInputStream fis = null;
OutputStream out1 = null;
try {
fis = new FileInputStream(file);
out1 = response.getOutputStream();
while ((i = fis.read(b)) > 0) {
out1.write(b, 0, i);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
out1.flush();
out1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
--------------------------------------------------------web.xml------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>DownloadAction</servlet-name>
<servlet-class>com.sh.struts.action.DownloadAction</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownloadAction</servlet-name>
<url-pattern>/downloadAction</url-pattern>
</servlet-mapping>
</web-app>
在服務(wù)器上下載則是:
Servlet:
package servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet {
private String contentType = "application/x-msdownload";
private String enc = "utf-8";
private String fileRoot = "";
public DownloadServlet() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String filepath = request.getParameter("filepath");
String Root = request.getRealPath("/");
// fileRoot = Root+"uploaddoc\\";
String fullFilePath = Root + fileRoot + filepath;
String FilePathR = fullFilePath.replaceAll("\\\\", "/");
/*讀取文件*/
File file = new File(FilePathR);
/*如果文件存在*/
if (file.exists()) {
String filename = URLEncoder.encode(file.getName(), enc);
response.reset();
response.setContentType(contentType);
response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
int fileLength = (int) file.length();
response.setContentLength(fileLength);
/*如果文件長(zhǎng)度大于0*/
if (fileLength != 0) {
/*創(chuàng)建輸入流*/
InputStream inStream = new FileInputStream(file);
byte[] buf = new byte[4096];
/*創(chuàng)建輸出流*/
ServletOutputStream servletOS = response.getOutputStream();
int readLength;
while (((readLength = inStream.read(buf)) != -1)) {
servletOS.write(buf, 0, readLength);
}
inStream.close();
servletOS.flush();
servletOS.close();
}
}
}
public void init(ServletConfig config) throws ServletException {
String tempStr = config.getInitParameter("contentType");
if (tempStr != null && !tempStr.equals("")) {
contentType = tempStr;
}
tempStr = config.getInitParameter("enc");
if (tempStr != null && !tempStr.equals("")) {
enc = tempStr;
}
tempStr = config.getInitParameter("fileRoot");
if (tempStr != null && !tempStr.equals("")) {
fileRoot = tempStr;
}
}
}
web.xml
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>DownloadServlet</servlet-name>
<servlet-class>servlet.DownloadServlet</servlet-class>
<init-param>
<param-name>fileRoot</param-name>
<param-value>uploaddoc</param-value>
</init-param>
<init-param>
<param-name>contentType</param-name>
<param-value>application/x-msdownload</param-value>
</init-param>
<init-param>
<param-name>enc</param-name>
<param-value>utf-8</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DownloadServlet</servlet-name>
<url-pattern>/down</url-pattern>
</servlet-mapping>
JSP頁(yè)面:
<a href="down?filepath=\20080914234530687.txt">下載</a>
接下拉介紹另外一種下載方法:
JSP頁(yè)面:
<body>
<a href="DocDownII.jsp?url=/uploaddoc/20080914234530687.txt">下載</a>
</body>
DocDownII.jsp頁(yè)面:
<%@ page language="java" import="com.jspsmart.upload.*" pageEncoding="UTF-8"%><%
//記得那個(gè)<%不要有空格
String url=request.getParameter("url");
//// 新建一個(gè)SmartUpload對(duì)象
SmartUpload su=new SmartUpload();
// 初始化
su.initialize(pageContext);
// 設(shè)定contentDisposition為null以禁止瀏覽器自動(dòng)打開(kāi)文件,
//保證點(diǎn)擊鏈接后是下載文件。若不設(shè)定,則下載的文件擴(kuò)展名為
//doc時(shí),瀏覽器將自動(dòng)用word打開(kāi)它。擴(kuò)展名為pdf時(shí),
//瀏覽器將用acrobat打開(kāi)。
su.setContentDisposition(null);
//下載開(kāi)始
su.downloadFile(url);
%>
注意,執(zhí)行下載的頁(yè)面,在Java腳本范圍外(即之外),不要包含HTML代碼、空格、回車或換行等字符,有的話將不能正確下載。不信的話,可以在上述源碼中%><%之間加入一個(gè)換行符,再下載一下,保證出錯(cuò)。因?yàn)樗绊懥朔祷亟o瀏覽器的數(shù)據(jù)流,導(dǎo)致解析出錯(cuò)。