Simple implementation of Servlet file download function

  • 2020-11-03 22:07:07
  • OfStack

The HttpServletResponse objects generated and passed by the Web container for Servlet can return not only HTML text, but also any other mainstream file format, such as.doc,.pdf,.jar,.avi and other content formats. These types of content are mainly embodied in the ES11en-ES12en field in the message header of the HTTP response message and in the response payload in the HTTP protocol.

content-type indicates to the browser that the content in the payload area is of type x, for example:.jar.
The content in the payload is the byte collection of the target file, which is in base 2 content format, rather than specific HTML-like text format content.

Thus, it can be said that Servlet can return anything it wants with the HttpServletResponse object, and can add any logical code, such as judgment permission logic, before deciding what it wants to return. Servlet can also be used to dynamically create what the user needs, or to send back bytes created in real time.

For example, you have a system where you get input parameters from the user, and then use those parameters to dynamically generate a sound and send it back. In other words, the voice does not have a seat on the server. The current Servlet needs to create such a voice and return it to the client in the response.

The specific code is as follows:


package down;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CodeServlet extends HttpServlet {

  
  private static final long serialVersionUID = -2142723162865292420L;

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setHeader("content-type", "application/jar");
    response.addHeader("content-disposition", "attachment;filename=utils.jar");
    ServletContext ctx = this.getServletContext();
    InputStream is = ctx.getResourceAsStream("/utils.jar");
    
    int read = 0;
    byte[] bytes = new byte[1024];
    
    OutputStream os = response.getOutputStream();
    while((read = is.read(bytes)) != -1) {
      os.write(bytes, 0, read);
    }
    os.flush();
    os.close();
  }
}

Description:

First of all, we need to set some properties of the HTTP protocol response message header through the instance of HttpServletResponse
response. addHeader () or response. setHeader () or response setIntHeader () function, two parameters, the first parameter is the property name, the second parameter is the attribute values, specific according to international standard MIME attribute to set, a lot of kinds of format of the file types in MIME will have corresponding, if by URL to specify a particular resource files directly, Apache server will generate the corresponding depending on the type of resource file on the server HTTP corresponding content - type type of message However, if the resource file is not specified directly by URL, but points to 1 Servlet, then the content-ES59en type in the response message needs to be specified explicitly through the code inside Servlet, otherwise different types of browsers will have different actions and it is very likely to crash the browser.

In the above example, the main idea is to specify the return type as.jar.

The second addHeader is the default name for the file. utils.jar is specified by the "content-ES73en" attribute. If not specified, the browser will default to the URL name of the current Servlet, such as ES76en.do, which means the extension becomes.do instead of.jar.

The rest of the code requires knowledge of ES83en.io.

The following is a piece of code found from the Internet, with a definite reference function:


 OutputStream o = response.getOutputStream();
 byte b[] = new byte[500];
 File fileLoad = new File("e:/tmpxls.xls");
 response.reset();
 //response.setCharacterEncoding("gb2312");
 response.setContentType("application/vnd.ms-excel");
 response
  .setHeader("content-disposition", "attachment; filename=abc.xls");
 long fileLength = fileLoad.length();  // Here, length() Returns the length of the file , In bytes ,Long type 
 String length1 = String.valueOf(fileLength);
 response.setHeader("Content_Length", length1); //content-length Refers to bytes of the payload (Byte) The length of the 
 FileInputStream in = new FileInputStream(fileLoad);
 int n;
 while ((n = in.read(b)) != -1) {
  o.write(b, 0, n);
 }
 in.close();
 o.close();

For another reference, see the blog post es92EN-Disposition usage and notes


Related articles: