第十一章_檔案下載

來源:互聯網
上載者:User

標籤:檔案下載

11.1、檔案下載概述

1、將響應的內容類型設定為檔案的內容類型。標題Content-type用來規定實體主體中的資料類型,包含媒體類型和子類型標識符。

2、添加一個名為Content-Disposition的HTTP回應標頭,給它賦值attachment;filename=filename,這裡的fileName是指在檔案下載對話方塊中顯示出來的預設檔案名稱。它通常與檔案名稱相同,但是也可以不同。

例如,以下就是將一個檔案發送到瀏覽器的代碼範例。

FileInputStream fis = new FileInputStream(file) ;

BufferedInputStream bis = new BufferedInputStream(fis) ;

byte[] bytes = new byte[bis.available()] ;

response.setContentType(contentType) ;

OutputStream os = response.getOutputStream() ;

bis.read(bytes) ;

os.write(bytes) ;

警告:一定要確保你沒有在無意中發送超出實際檔案內容以外的任何字元。這有可能在你毫不知情的情況下發生。例如,如果需要在JSP頁面中使用page指令,可以這麼寫:

<%@ page import=”java.io.FileInputStream”%>

<jsp:useBean id=”DBBeanId” scope=”page” class=”MyBean”>

在你毫不察覺的情況下,page指令後面的斷行符號分行符號就會被發送給瀏覽器。為了防止發送多餘的字元,需要像下面這樣編寫這個指令:

<%@ page import=”java.io.FileInputStream”

%><jsp:useBean id=”DBBeanId” scope=”page” class=”MyBean”>

 

11.2、範例1:隱藏資源

在下面這個程式中,我們用一個FileDownloadServlet servlet將secret.pdf檔案發送到瀏覽器。但是,只有授權使用者才能瀏覽。如果使用者沒有登入,應用程式就會跳轉到Login頁面。在這裡,使用者可以在表單中輸入使用者名稱和密碼,這些內容都將被提交給另一個Servlet:LoginServlet。

LoginServlet.java

package filedownloaded;import java.io.IOException;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;@WebServlet(urlPatterns = {"/login"})public class LoginServlet extends HttpServlet{private static final long serialVersionUID = 1L;public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {String userName = request.getParameter("userName") ;String password = request.getParameter("password") ;if(userName != null && userName.equals("ken")&& password != null && password.equals("secret")){HttpSession session = request.getSession(true) ;session.setAttribute("loggedIn", Boolean.TRUE);response.sendRedirect("download");return ;}else{RequestDispatcher dispatcher = request.getRequestDispatcher("/login.jsp") ;dispatcher.forward(request, response);}}}

login.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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'login.jsp' starting page</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="login" method="post">    <table>    <tr>    <td>User name: </td>    <td><input name="userName"/></td>    </tr>    <tr>    <td>Password: </td>    <td><input name="password" type="password"/></td>    </tr>    <tr>    <td colspan="2">    <input type="submit" value="login"/>    </td>    </tr>    </table>    </form>  </body></html>
FileDownloadServlet.java

package filedownloaded;import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;@WebServlet(urlPatterns = {"/download"})public class FileDownloadServlet extends HttpServlet{private static final long serialVersionUID = 1L;@Overridepublic void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {HttpSession session = req.getSession() ;if(session == null || session.getAttribute("loggedIn") == null){RequestDispatcher dispatcher = req.getRequestDispatcher("/login.jsp") ;dispatcher.forward(req, resp); return ;}String dataDirectory = req.getServletContext().getRealPath("/WEB-INF/data") ;File file = new File(dataDirectory, "secret.pdf") ;if(file.exists()){resp.setContentType("application/pdf");resp.addHeader("Content-Disposition", "attachment; filename=secret.pdf");byte[] buffer = new byte[1024] ;try(FileInputStream fis = new FileInputStream(file) ;BufferedInputStream bis = new BufferedInputStream(fis);OutputStream os = resp.getOutputStream()){int i = bis.read(buffer) ;while(i != -1){os.write(buffer, 0, i);i = bis.read(buffer) ;}}catch(IOException e){e.printStackTrace();}}}}


第十一章_檔案下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.