The function and usage of response.setContentType() and Content-Disposition in the header

1. response.setContentType() :

1.1 Overview:

Content type, generally refers to the Content-Type existing in a web page, which is used to define the type of network file and the encoding of the web page, and determine the format and encoding of the browser to read this file.
Correspondence between file extension and Content-type, see:

1.2 Common methods:

response.setContentType("text/html"); // the most popular one 
response.setContentType("text/css"); // Cascading Style Sheet 

2. Content-Disposition:

2.1 Overview

It is an extension of the MIME protocol. The MIME protocol instructs the MIME user agent how to display the attached file. The response header indicates in what form the content of the reply should be displayed, whether it is inline (that is, a web page or part of a web page), or as an attachment. The form is downloaded and saved locally
. When Internet Explorer receives the headers, it activates the file download dialog, whose filename box is automatically filled with the filename specified by the headers.

When the server sends a file to the browser, if it is a file type supported by the browser, it will generally be opened by the browser by default, such as txt, jpg, etc. If you need to prompt the user to save, you must use Content-Disposition for processing. (Knock on the blackboard, draw the key point) The key is to add attachment [attachment].
For example:


In this case, when the browser is opened, it will prompt to save or open. Even if you choose to open, it will use the associated program, such as Notepad, instead of IE to open directly.
Content-Disposition is to provide a default file name when the user wants to save the requested content as a file.
The specific definitions are as follows:

content-disposition ="Content-Disposition" ":"
                     *(";" disposition-param)
filename-param= "filename"  "=" quoted-string
disp-extension-token = token
token "=" ( token | quoted-string )

Common forms:

Content-Disposition: inline
Content-Disposition: attachment
Content-Disposition: attachment; filename="filename.jpg"

2.2 Example:

        fileName = URLEncoder.encode("导入模版.xlsx","utf-8");
        response.setHeader("Content-disposition","attachment; filename="+fileName);

Of course, the filename parameter can contain path information, but User-Agnet will ignore this information, and only use the last part of the path information as the file name. If the above header information is used when the response type is application/octet-stream, then the content cannot be displayed directly, but a "file download" dialog box pops up, and then the user decides to "open" or "save". .

Guess you like