Simple implementation of servlet file download function

The httpservletresponse object generated and passed by the web container for the servlet can return not only HTML text, but also any other mainstream file format, for example doc、. pdf、. jar、. AVI and other content format files These types of content are mainly reflected in the content type field of the message header and the response payload in the HTTP response message

Content type is to indicate to the browser that the content in the payload area is of a certain type, for example: Jar type content The content in the payload is the byte set of the target file, that is, the binary content format, rather than the specific text format content similar to HTML

Therefore, it can be said that the servlet can use the httpservletresponse object to return any content you want to return, and any logic code can be added before determining the specific content to return, such as judging the permission logic You can also use servlet to dynamically create the content required by users, or send back the bytes created in real time

For example, in a system, you need to get input parameters from the user, then use these parameters to dynamically generate a sound and send it back Originally, there was no sound. In other words, the sound does not have a file on the server. The current servlet needs to create such a sound, and then put it in the response and return it to the client

The specific codes are as follows:

explain:

First, you need to set some properties of the HTTP protocol response message header through the instance of httpservletresponse. This is through response Addheader() or response Setheader() or response The setintheader() function is completed with two parameters. The first parameter is the attribute name and the second parameter is the attribute value. The details should be formulated according to the mime attribute of the international standard. Many file types have corresponding in mime. If the specific resource file is specified directly through the URL, The Apache server will generate the content type of the corresponding HTTP message according to the resource file type on the server. However, if the resource file is not specified directly through the URL, but points to a servlet, the content type in the response message needs to be explicitly specified through code within the servlet, otherwise different kinds of browsers will have different actions, It is also likely to crash the browser. (see mime for details)

For another reference, see the blog post: content disposition usage and precautions

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>