HttpServletResponse Object Implementation File download

Source: Internet
Author: User

The Web server receives an HTTP request from the client, creating a Request object for each request, and a response object representing the response, respectively.
The request and response objects represent requests and responses, so we need to get the data submitted by the client, just find the request object. To output data to a client, you just need to find the response object.

First, HttpServletResponse object introduction

The HttpServletResponse object represents the response of the server. This object encapsulates the 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 sending the response header to the client (browser) related methods

  

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

  

1.4, the constant response status code
 
HttpServletResponse defines a number of constants for the status code (see the Servlet's API), which can be used when a response status code needs to be sent to the client, avoiding direct write numbers, and constants that correspond to common status codes:

Constants corresponding to status code 404

 

Constants corresponding to status code 200

  

Constants corresponding to status code 500

  

Ii. common applications of HttpServletResponse objects

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

Use OutputStream stream to output Chinese note the problem:

On the server side, the data is the Code table output, then control the client browser with 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 time to control the client browser to UTF-8 encoding open, otherwise display will appear in Chinese garbled, So how does the server side control the client browser 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 the OutputStream to flow to the client browser output "China" two characters

 PackageGacl.response.study;2  3 ImportJava.io.IOException;4 ImportJava.io.OutputStream;5 ImportJavax.servlet.ServletException;6 ImportJavax.servlet.http.HttpServlet;7 ImportJavax.servlet.http.HttpServletRequest;8 ImportJavax.servlet.http.HttpServletResponse;9 Ten  Public  class ResponseDemo01 extends httpservlet { One  A     Private Static Final LongSerialversionuid =4312868947607181532L -  -      Public void Doget(HttpServletRequest request, httpservletresponse response) 15throwsServletexception, IOException { -Outputchinesebyoutputstream (response);//Use OutputStream stream to output Chinese -} -      +     /**20 * Use outputstream stream output Chinese * @param request22 * @param response23 * @thro WS IOException * / -      Public void Outputchinesebyoutputstream(HttpServletResponse response)throwsioexception{ -         /** using OutputStream output Chinese Note: 27 * On the server side, the data is the Code table output, then control the client browser with the corresponding Code table open, 28 * For example: Outputstream.write ("China ". GetBytes (" UTF-8 "));//Use OutputStream flow to the client browser output Chinese, output in UTF-8 encoding 29 * At this time to control the client browser to UTF-8 encoding open, otherwise display will appear when the Chinese garbled, then in the service How does the server side control the client browser to display data in UTF-8 encoding? 30 * You can control the behavior of the browser by setting the response header, for example: * Response.setheader ("Content-type", "text/html;charset=utf-8");//By setting the response header control The browser displays the data in UTF-8 code. -String data ="China"; theOutputStream outputstream = Response.getoutputstream ();//Get OutputStream output stream *Response.setheader ("Content-type","Text/html;charset=utf-8");//By setting the response header control browser to display data in UTF-8 encoding, if not add this sentence, then the browser will display is garbled $         /**37 * Data.getbytes () is a process of converting characters into byte arrays, and this process will certainly go to the Code table, 38 * If it is a Chinese operating system environment, the default is to find the GB2312 code table, 39 * The process of converting a character to a byte array is to convert the Chinese characters to the corresponding number on the GB2312 's Code table 40 * For example: "Medium" on GB2312 's code table corresponds to the number 9841 * "Country" on the GB2312 Code table corresponds to the number is 9942 * * +         /**44 * GetBytes () method if no parameters, then according to the operating system's language environment to choose the Conversion Code table, if it is a Chinese operating system, then use the GB2312 code table * / $         byte[] Databytearr = Data.getbytes ("UTF-8");//Convert character to byte array, specify UTF-8 encoding for conversion -Outputstream.write (Databytearr);//using OutputStream to flow to the client output byte array -} the  -      Public void DoPost(HttpServletRequest request, httpservletresponse response) 51throwsServletexception, IOException { theDoget (request, response); -} Wu  -}

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

File download function is often used in web development, the use of HttpServletResponse object can be used to achieve file download

The implementation of the file download function idea:

1. Get the absolute path to the file you want to download

2. Get the file name to download

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

4. Get the file input stream to download

5. Create a data buffer

6. Get the OutputStream stream from the response object

7. Writing the FileInputStream stream to buffer buffers

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

Example: Using response for file download

  PackageGacl.response.study;ImportJava.io.FileInputStream;ImportJava.io.FileNotFoundException;ImportJava.io.FileReader;ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;ImportJava.net.URLEncoder;ImportJavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/** * @author gacl * File Download * *  Public  class ResponseDemo02 extends httpservlet {      Public void Doget(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {downloadfilebyoutputstream (response);//download files via OutputStream stream}/** * Download file via outputstream stream * @param response * @throws filenotfoundexception *
     
       @throws IOException *
      /     Private void Downloadfilebyoutputstream(HttpServletResponse response)throwsFileNotFoundException, IOException {//1. Get the absolute path to the file you want to downloadString Realpath = This. Getservletcontext (). Getrealpath ("/download/1.jpg");//2. Get the file name to downloadString fileName = realpath.substring (Realpath.lastindexof ("\\")+1);//3. Setting the Content-disposition response header to control the browser to open the file as downloadedResponse.setheader ("Content-disposition","Attachment;filename="+filename);//4. Getting the file input stream to downloadInputStream in =NewFileInputStream (Realpath);intLen =0;//5. Creating a data buffer         byte[] buffer =New byte[1024x768];//6. Getting the OutputStream stream from a response objectOutputStream out = Response.getoutputstream ();//7. Writing fileinputstream streams to buffer buffers          while(len = in.read (buffer)) >0) {//8. Using OutputStream to output buffer data to the client browserOut.write (Buffer,0, Len);     } in.close (); } Public void DoPost(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {doget (request, response); } }

The results of the operation are as follows:

Example: Using response to implement Chinese file download

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

 PackageGacl.response.study;ImportJava.io.FileInputStream;ImportJava.io.FileNotFoundException;ImportJava.io.FileReader;ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;ImportJava.net.URLEncoder;ImportJavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/** * @author gacl * File Download * *  Public  class ResponseDemo02 extends httpservlet {      Public void Doget(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {downloadchinesefilebyoutputstream (response);//Download Chinese file}/** * Download Chinese file, chinese file download, file name is URL encoded, otherwise the file name garbled * @param response * @throws FILENOTF Oundexception * @throws ioexception * *     Private void Downloadchinesefilebyoutputstream(HttpServletResponse response)throwsFileNotFoundException, IOException {String Realpath = This. Getservletcontext (). Getrealpath ("/download/Zhangjiajie National Forest Park. JPG ");//Get the absolute path to the file to be downloadedString fileName = realpath.substring (Realpath.lastindexof ("\\")+1);//Get the file name to download         //Set Content-disposition response header control browser to download the form of open file, Chinese file name to use the Urlencoder.encode method to encode, otherwise the file name garbledResponse.setheader ("Content-disposition","Attachment;filename="+urlencoder.encode (FileName,"UTF-8")); InputStream in =NewFileInputStream (Realpath);//Get file input stream         intLen =0;byte[] buffer =New byte[1024x768]; OutputStream out = Response.getoutputstream (); while(len = in.read (buffer)) >0) {out.write (buffer,0, Len);//Output buffer data to client browser} in.close (); } Public void DoPost(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {doget (request, response); } }

The results of the operation are as follows:

* * Output Chinese data to client browser can use OutputStream stream
You can also use the PrintWriter stream
PrintWriter Flow detailed description see the following blog post
http://www.cnblogs.com/xdp-gacl/p/3789624.html**

HttpServletResponse Object Implementation 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.