When you serve a document from a Web server, you might want to immediately prompt the user to save the file directly to the user's disk, without opening it in the browser. however, for known mime (Multipurpose Internet Mail Extensions) types such as Microsoft Word ("application/MS-word"), the default behavior is to open the document in Internet Explorer.
You can use the content-Disposition Header to override this default behavior. Its format is:
Content-disposition: attachment; filename=fname.ext
Content-disposition is an extension to the MIME protocol that instructs a MIME user agent on how it should display an attached file. The range of valid values for content-disposition are discussed in Request for Comment (RFC) 1806 (see the "References" section of this article). This article focuses on the "attachment" argument, which instructs a user agent (in this case, Internet Explorer) to save a file to disk instead of saving it inline.
When Internet Explorer receives the header, it raises a File Download dialog box whose file name box is automatically populated with the file name that is specified in the header. (Note that this is by design; there is no way to use this feature to save a document to the user's computer without prompting him or her for a save location.)
In addition:
During web development, you may encounter the following requirements:
A file of a certain type or a known MIME type (for example, *. gif; *. txt; *. htm) is expected to pop up the "File Download" dialog box during access.
You must specify the file name when downloading the client.
You want to display a file directly in the browser instead of the file download dialog box.
You can use the content-Disposition attribute to solve the preceding requirements. The following is a sample code:
response.setHeader("Content-disposition", "attachment;filename=" + fileName)
Content-disposition is the attribute name.
Attachment indicates downloading as an attachment. If you want to open it on the page, change it to inline.
If filename is Chinese, garbled characters will appear. There are two solutions:
- Use the filename = new string (filename. getbytes (), "ISO8859-1") Statement
- Use the filename = httputility. urlencode (filename, system. Text. encoding. utf8) Statement