心得2--ダウンロードリソースの紹介、ケーススタディの詳細

6744 ワード

1.Webアプリケーションにおけるファイルダウンロードを実現する2つの方式
ハイパーリンクはダウンロードリソースを直接指し、プログラムがダウンロードを実現するには2つの応答ヘッダを設定する必要がある.
Content-Typeの値は、アプリケーション/x-msdownloadに設定します.Webサーバは、出力されるコンテンツのタイプが通常のテキストファイルやHTMLファイルではなく、ローカルに保存するダウンロードファイルであることをブラウザに伝える必要があります.
Webサーバは、ブラウザが対応するエンティティコンテンツを直接処理するのではなく、ユーザーが選択して対応するエンティティコンテンツをファイルに保存することを望んでいます.これはContent-Dispositionヘッダを設定する必要があります.このヘッダは、受信プログラムがデータコンテンツを処理する方式を指定し、HTTPアプリケーションではattachmentのみが標準方式であり、attachmentはユーザの介入を要求することを示す.attachmentの後にfilenameパラメータを指定することもできます.このパラメータは、サーバがブラウザにエンティティコンテンツをファイルに保存することを推奨するファイル名です.Content-Dispositionを設定する前にContent-Typeを指定する必要があります.
ダウンロードするファイルは様々な種類のファイルであってもよいので、ファイルをクライアントに転送するには、そのコンテンツをバイナリとして処理する必要があるので、メソッドを呼び出してサービス・オutputStreamオブジェクトを返してクライアントにファイルコンテンツを書き込む必要があります.                       
2.ダウンロード事例
アップロードディレクトリの下にあるすべてのファイルをユーザーに表示し、ダウンロードを完了できます.
(あるフォルダの下にあるすべてのファイルを読み取り、集合の中にリストを保存し、request役割ドメインの範囲に保存する)ListFileSerbelt-(すべてのファイルリストを表示する)Listfiles.jsp---DownloaServeret.java
3.理論を少し話して気絶したのではないでしょうか.では、実例を分析しましょう.
          listFile.jsp

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

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

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

<html>

  <head>

    

    <title>My JSP 'download.jsp' starting page</title>

    

  </head>

  

  <body>

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

      <c:url var="url" value="/Download">

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

      </c:url>

         :${ me.value }    

      <a href="${ url }">  </a><br><br>

      </c:forEach>

  </body>

</html>

           ListFile.java

package com.csdn.servlet;

 

import java.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 class ListFile extends HttpServlet {

 

   public void doGet(HttpServletRequest request, HttpServletResponse response)

        throws ServletException, IOException { 

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

      Map map = new HashMap();

      this.getListFile(new File(filePath), map);

      request.setAttribute("map",map);

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

 

   }

    private void getListFile(File file,Map map){

      //        upload            

      if(file.isFile()){

        String uuidName = file.getName();

        String realName = uuidName.substring(uuidName.indexOf("_")+1);

        map.put(uuidName,realName);

      }else{

        File[] files = file.listFiles();

        for(File f : files){

           getListFile(f,map);

        }

      }

    } 

   public void doPost(HttpServletRequest request, HttpServletResponse response)

        throws ServletException, IOException {

      doGet(request, response);

   }

}

          Download.java

package com.csdn.servlet;

 

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 Download extends HttpServlet {

 

   public void doGet(HttpServletRequest request, HttpServletResponse response)

        throws ServletException, IOException {

      //          

      String fileName = request.getParameter("fileName");

      fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");

      String savePath = this.getPath(this.getRealName(fileName));

      //               file   

      File file = new File(savePath+"\\"+fileName);

      //    file    ,             

      if(!file.exists()){

        request.setAttribute("message2","         ");

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

      }

      //     ,            ,                  ,           ,     ,            

      response.setHeader("content-disposition","attachment;fileName="+URLEncoder.encode(this.getRealName(fileName),"UTF-8"));

      FileInputStream in = new FileInputStream(file);

      OutputStream out = response.getOutputStream();

      byte[] buf = new byte[1024];

      int len = 0;

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

        out.write(buf,0,len);

      }

      in.close();

   }

   public String getPath(String fileName){

      int dir1 = fileName.hashCode()&0xf;

      int dir2 = (fileName.hashCode()>>4)&0xf;

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

      return savePath;

   }

   public String getRealName(String fileName){

      String realName = fileName.substring(fileName.indexOf("_")+1);

      return realName;

   }

   public void doPost(HttpServletRequest request, HttpServletResponse response)

        throws ServletException, IOException {

      doGet(request, response);

   }

}