1. 程式人生 > >java下載檔案案例(帶原始碼)

java下載檔案案例(帶原始碼)

前言:

web開發中上傳和下載是最基本的內容了。前幾天寫了一篇上傳的案例,今天總結一下下載。

案例說明:

1.本案例是使用myeclipse編寫
2.需要下載的檔案存放的 /download_demo/WebRoot/WEB-INF/attachment  目錄下面---這裡我只是放進去了測試檔案

下載檔案思路:

1.得到伺服器上面的檔案File
2.得到輸入流,將檔案流化
3.得到servlet輸出流,將檔案已流的方式寫到客戶端

看懂案例中的需要的知識點:

1.servlet的配置
2.filter的配置
3.java檔案的基礎知識
4.java流的知識

前臺頁面程式碼:一、index.jsp頁面

功能:點選按鈕,進入下載檔案頁面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML>
<html>
  <head>
<base href="<%=basePath%>"> <title>download demo</title> <meta charset="UTF-8"> <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"> --> <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.js"></script> <script type="text/javascript"> $(function(){ $("#download").on("click",function(){ window.open("download/show"); }); }); </script> </head> <body> <input type="button" value="點我進入下載頁面" id="download"/> </body> </html>

前臺頁面:二、download.jsp 頁面

作用:下載檔案介面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML>
<html>
  <head>
    <base href="<%=basePath%>">

    <title>download demo</title>
    <meta charset="UTF-8">  
    <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">
    -->

    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.js"></script>

  </head>

  <body>
        <!-- 遍歷檔案 -->
        <c:forEach var="file" items="${files}" varStatus="status">
            <span>${file.name}</span><a href="download/downloadfile?fileName=${file.name}">下載</a>
            <br>
        </c:forEach>
  </body>
</html>

後端程式碼:一、下載控制器(servlet) —核心程式碼

package cn.cupcat.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

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

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("我進入了post方法!");

        /*測試開始*/
        /*
            String uri = request.getRequestURI();// /download_demo/download/show
            StringBuffer url = request.getRequestURL();//http://127.0.0.1:8080/download_demo/download/show
            String servletPath = request.getServletPath();// /download
            String serverName = request.getServerName();// 127.0.0.1 
            String servletPath = request.getPathInfo();// /show
        */

        /*測試結束*/
        String servletPath = request.getPathInfo();// /show


        String relativePath = File.separatorChar + "WEB-INF"+ File.separatorChar + "attachment";
        String absolutePath = request.getServletContext().getRealPath(relativePath);

        if(servletPath.equalsIgnoreCase("/show")){
            File file = new File(absolutePath);

            if(file.exists()){
                if(file.isDirectory()){
                    File[] files = file.listFiles();
                    request.setAttribute("files", files);

                }
            }

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

        }else if(servletPath.equalsIgnoreCase("/downloadfile")){
            String fileName = request.getParameter("fileName");
            String fileAbosultePath = absolutePath +File.separatorChar+ fileName;

            File file = new File(fileAbosultePath);
            if(file.exists()){//file存在
                if(file.isFile()){//file是一個檔案

                    FileInputStream fis = new FileInputStream(file);
                    BufferedInputStream bis = new BufferedInputStream(fis);

                    byte[] buff = new byte[4096];
                    int readSize ;
                    ServletOutputStream outputStream = response.getOutputStream();

                    while((readSize = bis.read(buff)) != -1){
                        outputStream.write(buff, 0, readSize);
                    }

                     //1.設定檔案ContentType型別,這樣設定,會自動判斷下載檔案型別  
                    response.setContentType("multipart/form-data"); 

                    //2.設定檔案頭:最後一個引數是設定下載檔名(假如我們叫a.pdf)  
                    response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(file.getName(), "UTF-8"));  


                    bis.close();

                    outputStream.close();
                }
            }

        }else{
            System.out.println("沒有用到!");
        }









    }



    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("我進入了get方法!");
        this.doPost(req, resp);

    }




}

後端程式碼:二、過濾器(filter) —同一編碼

package cn.cupcat.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UnicodeFilter implements Filter{

    @Override
    public void destroy() {


    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
            FilterChain arg2) throws IOException, ServletException {
        if(arg0 instanceof HttpServletRequest){
            System.out.println("進入了過濾器");
            HttpServletRequest request = (HttpServletRequest)arg0;
            request.setCharacterEncoding("UTF-8"); //設定編碼,防止後臺得到中文亂碼
        }
        if (arg1 instanceof HttpServletResponse){
            HttpServletResponse response = (HttpServletResponse)arg1;
            response.setCharacterEncoding("UTF-8");//設定編碼,防止返回客戶端亂碼
        }
        arg2.doFilter(arg0, arg1);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}

配置檔案:web.xml —配置servlet、filter

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>download_demo</display-name>

  <!--   下載servlet開始 -->
  <servlet>
        <servlet-name>download</servlet-name>
        <servlet-class>cn.cupcat.controller.DownloadController</servlet-class>
  </servlet>
  <servlet-mapping>
        <servlet-name>download</servlet-name>
        <url-pattern>/download/*</url-pattern>
  </servlet-mapping>
  <!--   下載servlet結束 -->




  <!--  同一編碼 過濾器開始 -->
  <filter>
        <filter-name>unicode</filter-name>
        <filter-class>cn.cupcat.filter.UnicodeFilter</filter-class>
  </filter>
  <filter-mapping>
        <filter-name>unicode</filter-name>
        <!--  這裡指定filter只對servlet的name為upload生效  -->    
        <url-pattern>/*</url-pattern>
  </filter-mapping>
   <!--  同一編碼 過濾器結束 -->


  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

注意:

//1.設定檔案ContentType型別,這樣設定,會自動判斷下載檔案型別  
response.setContentType("multipart/form-data");


 //2.設定檔案頭:最後一個引數是設定下載檔名(假如我們叫a.pdf)  
 response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(file.getName(), "UTF-8")); 



說明:
    1.第一句是設定返回客戶端的二進位制檔案,客戶端可以直接下載
    2.第二句是設定返下載後的檔名

專案原始碼下載地址:

http://download.csdn.net/detail/xinghuo0007/9858034