HttpServletResponse Object Implementation File download

Source: Internet
Author: User

The Web server receives the HTTP request from the client and, for each request, creates a response object that represents the requested request object, and represents the response.
The request and response objects represent requests and responses, so we need to get the data submitted by the client, just to find the request object. To output data to the client, just look for the response object.

Introduction of HttpServletResponse Object

The HttpServletResponse object represents the response of the server. This object encapsulates a method of sending data to the client, sending a response header, and sending a response status code. Look at the HttpServletResponse API to see these related methods.

1.1, responsible for sending data to the client (browser) related methods

  

1.2, responsible for the client (browser) to send the response head of the relevant methods

  

1.3, responsible for sending to the client (browser) response status code related methods

  

1.4, the response status Code constants
 
HttpServletResponse defines a number of status code constants (you can view the Servlet API), and when you need to send a response status code to the client, you can use these constants to avoid direct-write numbers and constants that are common in status codes:

Status code 404 the corresponding constant

 

Status code 200 the corresponding constant

  

Status code 500 the corresponding constant

  

Ii. common applications of HttpServletResponse objects

2.1, using OutputStream flow to the client browser output Chinese data

Use OutputStream flow to export Chinese attention issues:

On the server side, the data is in which code table output, it is necessary to control the client browser to the corresponding code table open, such as: Outputstream.write ("China". GetBytes ("UTF-8")); Use OutputStream flow to the client browser output Chinese, to UTF-8 encoding for output, at this point to control the client browser to UTF-8 code open, otherwise the display will appear in Chinese garbled, So how do you control the client browser on the server side to display the data in UTF-8 encoding? You can control the behavior of the browser by setting the response header, for example: Response.setheader ("Content-type", "Text/html;charset=utf-8"), and by setting the response header to control the browser to display the data in UTF-8 encoding.

Example: Using OutputStream flow to the client browser output "China" two Chinese characters

Package gacl.response.study;
 2 3 Import java.io.IOException;
 4 Import Java.io.OutputStream;
 5 Import javax.servlet.ServletException;
 6 Import Javax.servlet.http.HttpServlet;
 7 Import Javax.servlet.http.HttpServletRequest;
 8 Import Javax.servlet.http.HttpServletResponse; 9 public class ResponseDemo01 extends HttpServlet {One private static final long Serialversionuid = 4312868947
607181532L; Doget public void (HttpServletRequest request, httpservletresponse response) throws Servletexcept      Ion, IOException {outputchinesebyoutputstream (response);//Use OutputStream Stream output Chinese 17} 18 19/** 20     * @param Request * @param response * @throws IOException 24/25 by using OutputStream flow output public void Outputchinesebyoutputstream (HttpServletResponse response) throws ioexception{26/** use OutputStream Output Chinese Note: 27 * On the server side, the data is in which code table output, then it is necessary to control the client browser to the corresponding Code table open, 28 * For example: Outputstream.writE ("China". GetBytes ("UTF-8"))//Use OutputStream flow to the client browser output Chinese, UTF-8 encoding for output 29 * At this point to control the client browser to the UTF-8 code to open, otherwise the display will appear in Chinese garbled
, then how to control the client browser on the server side to display the data in UTF-8 encoding. 30 * You can control the behavior of the browser by setting the response head, such as: Response.setheader ("Content-type", "Text/html;charset=utf-8"), and/or by setting the response header control
Browser to display data in UTF-8 encoding/n/a String data = "China"; OutputStream outputstream = Response.getoutputstream ();//get OutputStream output stream Response.setheader ("Conte Nt-type "," text/html;charset=utf-8 ");//By setting the response head to control the browser to display the data in UTF-8 encoding, if not add this sentence, then the browser will display garbled/** Panax Notoginseng * data.ge Tbytes () is a process of converting characters into byte arrays, which is sure to check the Code table, 38 * If the operating system environment in Chinese, the default is to find the Code table to check GB2312, 39 * The process of converting a character to a byte array is to convert the Chinese characters to G         B2312 's Code table corresponds to the number 40 * For example: "Medium" on the GB2312 's code table corresponds to the number is 98 41 * "Country" on the GB2312 of the Code table corresponds to the number 99 42 * * * 43  /** * GetBytes () method if not with parameters, then the operating system according to the language environment to select the Conversion Code table, if the Chinese operating system, then the use of GB2312 code table * * * byte[] Databytearr = Data.getbytes ("UTF-8");//convert character to WordAn array of sections that specifies to convert the Outputstream.write (Databytearr) with UTF-8 encoding;//use OutputStream to flow to client output byte array         DoPost (HttpServletRequest request, httpservletresponse response) Wuyi throws Servletexception, IOException {52
Doget (request, response); 53} 54 55}

The results of the operation are as follows:

After the client browser receives the data, it parses the data according to the character encoding set on the response header, as follows:

2.2, File download

The file downloading function is the function which frequently uses in the Web development, uses the HttpServletResponse object to be possible to realize the file the downloading

The implementation of the file download function:

1. Get the absolute path to the file to download

2. Get the file name to download

3. Set the Content-disposition response header to control the browser to download the form to open the file

4. Get the file input stream to download

5. Create a data buffer

6. Get OutputStream Stream by response object

7. Writes the FileInputStream stream to the buffer buffer

8. Use OutputStream to output buffer data to the client browser

Example: Using response to implement file downloads

 Package gacl.response.study;
 2 Import Java.io.FileInputStream;
 3 Import java.io.FileNotFoundException;
 4 Import Java.io.FileReader;
 5 Import java.io.IOException;
 6 Import Java.io.InputStream;
 7 Import Java.io.OutputStream;
 8 Import Java.io.PrintWriter;
9 Import Java.net.URLEncoder;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse; /** * @author gacl 16 * File Download/* Public class ResponseDemo02 extends HttpServlet {The public void do         Get (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {22       Downloadfilebyoutputstream (response)//download file, via OutputStream Stream 23} 24 25/** 26 * Download file through OutputStream stream 27 * @param response * @throws filenotfoundexception * @throws ioexception/Private VO ID Downloadfilebyoutputstream (httpserVletresponse response) throws FileNotFoundException, IOException {33//1. Gets the absolute path 34 of the file to download
String Realpath = This.getservletcontext (). Getrealpath ("/download/1.jpg");
35//2. Gets the file name to be downloaded. String filename = realpath.substring (realpath.lastindexof ("\") +1); 37//3. Set the Content-disposition response header to control the browser to download the form open file Response.setheader ("Content-disposition", "Attachment;fi
Lename= "+filename);
39//4. Gets the file input stream to download inputstream in = new FileInputStream (Realpath);
int len = 0;
42//5. Create data buffer byte[] buffer = new byte[1024];
44//6. Get OutputStream stream OutputStream out = Response.getoutputstream () by response object; 46//7. Writes the FileInputStream stream to the buffer buffer (len = in.read (buffer) > 0) {48//8. Using OUTPUTST
Ream outputs the buffer data to the client browser out.write (Buffer,0,len);
Wuyi In.close (); The public void DoPost (HttpServletRequest reqUest, HttpServletResponse response) throws Servletexception, IOException (Request, Doget
SE); 57} 58}

The results of the run are as follows:

Example: Using response to implement Chinese file download

When downloading Chinese files, it is necessary to note that the Chinese file name should be encoded using the Urlencoder.encode method (Urlencoder.encode (FileName, "character encoding"), otherwise the file name will appear garbled.
  

Package gacl.response.study;
 2 Import Java.io.FileInputStream;
 3 Import java.io.FileNotFoundException;
 4 Import Java.io.FileReader;
 5 Import java.io.IOException;
 6 Import Java.io.InputStream;
 7 Import Java.io.OutputStream;
 8 Import Java.io.PrintWriter;
9 Import Java.net.URLEncoder;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse; /** * @author gacl 16 * File Download/* Public class ResponseDemo02 extends HttpServlet {The public void do         Get (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {22 Downloadchinesefilebyoutputstream (response)//download Chinese file 23} 24 25/** 26 * Download Chinese file, the file name should be encoded by URL when downloading, otherwise     File name garbled * @param response * @throws FileNotFoundException * @throws IOException 30/31 private void DOWNLOADCHINESEFILEBYOUTPUtstream (HttpServletResponse response) throws FileNotFoundException, IOException {a String Realpa th = This.getservletcontext () getrealpath ("/download/Zhangjiajie National Forest Park".         JPG ")//Gets the absolute path to the file to be downloaded-String fileName = realpath.substring (Realpath.lastindexof (" \ ") +1); Get the file name to download 35 Set Content-disposition response header control browser to download the form to open the file, the Chinese file name to use the Urlencoder.encode method to encode, otherwise the filename will appear garbled response.setheader ("cont
Ent-disposition "," attachment;filename= "+urlencoder.encode (filename," UTF-8 "));
Panax Notoginseng InputStream in = new FileInputStream (realpath);//get file input stream int len = 0;
byte[] buffer = new byte[1024];
OutputStream out = Response.getoutputstream (); 
(len = in.read (buffer) > 0) {out.write (Buffer,0,len);//output buffer data to client browser 43}
In.close ();  DoPost public void (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException{doget (request, response); 50} 51} 

The results of the run are as follows:

Output Chinese data to the client browser you can use the OutputStream stream
You can also use the PrintWriter stream
PrintWriter Flow detailed description see the following blog

Http://www.cnblogs.com/xdp-gacl/p/3789624.html

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.