Chapter 2 _ File Download

Source: Internet
Author: User
11.1 File Download Overview

1. Set the response content type to the file content type. The header Content-Type specifies the data type in the entity body, including the media type and child type identifier.

2. Add an HTTP response header named content-Disposition and assign attachment; filename = filename to it. The filename here refers to the default file name displayed in the file download dialog box. It is usually the same as the file name, but it can also be different.

For example, the following is a sample code that sends a file to a browser.

Fileinputstream FCM = new fileinputstream (File );

Bufferedinputstream Bis = new bufferedinputstream (FCM );

Byte [] bytes = new byte [bis. Available ()];

Response. setcontenttype (contenttype );

Outputstream OS = response. getoutputstream ();

Bis. Read (bytes );

OS. Write (bytes );

Warning make sure that you have not inadvertently sent any characters beyond the actual file content. This may happen without your knowledge. For example, if you need to use the page command in the JSP page, you can write the following code:

<% @ Page import = "Java. Io. fileinputstream" %>

<JSP: usebean id = "dbbeanid" scope = "page" class = "mybean">

Without notice, the carriage return line break following the page command will be sent to the browser. To prevent extra characters from being sent, you need to write this command as follows:

<% @ Page import = "Java. Io. fileinputstream"

%> <JSP: usebean id = "dbbeanid" scope = "page" class = "mybean">

 

11.2. Example 1: Hide Resources

In the following program, we use a filedownloadservlet servletto send the secret.pdf file to the browser. However, only authorized users can browse. If the user does not log on, the application will jump to the login page. Here, you can enter the user name and password in the form, and the content will be submitted to another 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">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();}}}}


Chapter 2 _ File Download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.