Response download file for javaweb programming
#Daily sharing income, welcome to pay attention to learning computer, I love computer! Better follow-up#
About HttpServletResponse
When the web server receives an http request from the client, the server will create an object representing the request, called HttpServletRequest; An object representing the response, called HttpServletResponse;
The simple understanding is:
-
If you need to obtain the parameters requested by the client, use HttpServletRequest;
-
If you want to provide some response information to the client, use HttpServletResponse.
A simple classification of HttpServletResponse:
-
Methods responsible for sending some data to the client browser:
ServletOutputStream getOutputStream() throws IOException; PrintWriter getWriter() throws IOException;
-
Methods responsible for sending some response headers to the browser:
void sendError(int var1, String var2) throws IOException; void sendError(int var1) throws IOException; void sendRedirect(String var1) throws IOException; void setDateHeader(String var1, long var2); void addDateHeader(String var1, long var2); void setHeader(String var1, String var2); void addHeader(String var1, String var2); void setIntHeader(String var1, int var2); void addIntHeader(String var1, int var2); void setStatus(int var1);
-
Status code responsible for response
int SC_CONTINUE = 100; int SC_SWITCHING_PROTOCOLS = 101; int SC_OK = 200; //common int SC_CREATED = 201; int SC_ACCEPTED = 202; int SC_NON_AUTHORITATIVE_INFORMATION = 203; int SC_NO_CONTENT = 204; int SC_RESET_CONTENT = 205; int SC_PARTIAL_CONTENT = 206; int SC_MULTIPLE_CHOICES = 300; //common int SC_MOVED_PERMANENTLY = 301; int SC_MOVED_TEMPORARILY = 302; int SC_FOUND = 302; int SC_SEE_OTHER = 303; int SC_NOT_MODIFIED = 304; int SC_USE_PROXY = 305; int SC_TEMPORARY_REDIRECT = 307; int SC_BAD_REQUEST = 400; int SC_UNAUTHORIZED = 401; int SC_PAYMENT_REQUIRED = 402; int SC_FORBIDDEN = 403; int SC_NOT_FOUND = 404; //common int SC_METHOD_NOT_ALLOWED = 405; int SC_NOT_ACCEPTABLE = 406; int SC_PROXY_AUTHENTICATION_REQUIRED = 407; int SC_REQUEST_TIMEOUT = 408; int SC_CONFLICT = 409; int SC_GONE = 410; int SC_LENGTH_REQUIRED = 411; int SC_PRECONDITION_FAILED = 412; int SC_REQUEST_ENTITY_TOO_LARGE = 413; int SC_REQUEST_URI_TOO_LONG = 414; int SC_UNSUPPORTED_MEDIA_TYPE = 415; int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416; int SC_EXPECTATION_FAILED = 417; int SC_INTERNAL_SERVER_ERROR = 500; //common int SC_NOT_IMPLEMENTED = 501; int SC_BAD_GATEWAY = 502; int SC_SERVICE_UNAVAILABLE = 503; int SC_GATEWAY_TIMEOUT = 504; int SC_HTTP_VERSION_NOT_SUPPORTED = 505;
About response status codes: 404 errors, 500 errors, etc. are often encountered during web browsing. These are called response status codes.
Common applications of HttpServletResponse
-
Input some data to the browser;
-
Download File
-
Prepare the path to download the file
-
Prepare the file name of the file to be downloaded
-
Set up browser support Downloads
-
Get input stream to downloaded file
-
Create a buffer to write to the stream
-
Get OutputStream object
-
Writes the stream of the FileOutputStream object to the buffer buffer created previously
-
Use the OutputStream object to output the data in the buffer to your own client
-
Example:
Configuration xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0" metadata-complete="true"> <servlet> <servlet-name>fileDownload</servlet-name> <servlet-class>psl.wong.servlet.FileServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>fileDownload</servlet-name> <url-pattern>/down</url-pattern> </servlet-mapping> </web-app>
Primary code:
package psl.wong.servlet; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileInputStream; import java.io.IOException; import java.net.URLEncoder; public class FileServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Download File //- Prepare the path to download the file String realPath = "D:\\Program Files\\ideaIU\\IdeaWorkspace\\Javaweb_02_Servlet\\Response\\src\\main\\resources\\tencent.PNG"; //source file URL System.out.println("Path to download file:"+realPath); //- Prepare the file name of the file to be downloaded String fileName = realPath.substring(realPath.lastIndexOf("\\")+1); //Get to last "/"The following data is the file name. //- Set up browser support Downloads resp.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")); //- Get input stream to downloaded file FileInputStream in = new FileInputStream(realPath); //- Create a buffer to write to the stream int len=0; byte[] bytes = new byte[1024]; //- obtain OutputStream object ServletOutputStream outputStream = resp.getOutputStream(); //- take FileOutputStream Object to the previously created buffer In buffer,apply OutputStream Object will buffer The data in the buffer is output to its own client while ((len=in.read(bytes))>0){ outputStream.write(bytes,0,len); } outputStream.close(); in.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }