少年阿宾

那些青春的岁月

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks

<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 = "";

 

 

       /**

        * 初始化contentTypeencfileRoot

        */

       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);

              /*如果文件长度大于0*/

               if (fileLength != 0) {

                   /*创建输入流*/

                   InputStream inStream = new FileInputStream(file);

                   byte[] buf = new byte[4096];

                   /*创建输出流*/

                   ServletOutputStream servletOS = response.getOutputStream();

                   int readLength;

                   while (((readLength = inStream.read(buf)) != -1)) {

                       servletOS.write(buf, 0, readLength);

                   }

                   inStream.close();

                   servletOS.flush();

                   servletOS.close();

               }

           }

       }

}

 

 

Jsp页面:

<a href=”down?filepath=/aa.doc”>下载</a>

 

下面还有一个例子:

--------------------------------------------------------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>

 

在服务器上下载则是:

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);
            /*如果文件长度大于0*/
            if (fileLength != 0) {
                /*创建输入流*/
                InputStream inStream = new FileInputStream(file);
                byte[] buf = new byte[4096];
                /*创建输出流*/
                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页面:

<a href="down?filepath=\20080914234530687.txt">下载</a> 

 

接下拉介绍另外一种下载方法:

JSP页面:

 <body>
    <a href="DocDownII.jsp?url=/uploaddoc/20080914234530687.txt">下载</a>
  </body>

DocDownII.jsp页面:

<%@ page language="java" import="com.jspsmart.upload.*" pageEncoding="UTF-8"%><%
//记得那个<%不要有空格
String url=request.getParameter("url");
//// 新建一个SmartUpload对象
SmartUpload su=new SmartUpload();
// 初始化
su.initialize(pageContext);
// 设定contentDisposition为null以禁止浏览器自动打开文件,   
//保证点击链接后是下载文件。若不设定,则下载的文件扩展名为   
//doc时,浏览器将自动用word打开它。扩展名为pdf时,   
//浏览器将用acrobat打开。 
su.setContentDisposition(null);
//下载开始
su.downloadFile(url);
%>

 注意,执行下载的页面,在Java脚本范围外(即之外),不要包含HTML代码、空格、回车或换行等字符,有的话将不能正确下载。不信的话,可以在上述源码中%><%之间加入一个换行符,再下载一下,保证出错。因为它影响了返回给浏览器的数据流,导致解析出错。

 

posted on 2011-10-31 20:15 abin 阅读(1162) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: