少年阿賓

          那些青春的歲月

            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 閱讀(1164) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 宾川县| 托克逊县| 东港市| 宜黄县| 呼伦贝尔市| 平湖市| 巧家县| 东海县| 新乡市| 平塘县| 阳曲县| 德惠市| 黄梅县| 内江市| 观塘区| 宿迁市| 常山县| 南雄市| 武宣县| 襄城县| 孙吴县| 惠安县| 昌图县| 昂仁县| 洛浦县| 台江县| 卫辉市| 疏勒县| 虹口区| 汽车| 宜章县| 容城县| 安化县| 察隅县| 临西县| 淮滨县| 炎陵县| 浪卡子县| 区。| 阿合奇县| 石河子市|