Start with the response. setcontenttype () method.

Source: Internet
Author: User
Tags server memory gtar
The article is not original. For more information, see the end of this article!
The following table lists common MIME types:

Serial number

Content type

File Extension

Description

1

Application/MSWord

Doc

Microsoft Word

2

Application/octet-stream Bin

Dms lha lzh EXE class

Executable program

3

Application/PDF

PDF

Adobe Acrobat

4

Application/postscript

AI EPS PS

Postscript

5

APPICATION/PowerPoint

PPT

Microsoft PowerPoint

6

APPICATION/RTF

RTF

RTF Format

7

APPICATION/X-compress

Z

UNIX compressed file

8

Application/X-Gzip

GZ

Gzip

9

Application/X-gtar

Gtar

Tar document (GNU format)

10

Application/X-Shockwave-flash

SWF

Macromedia Flash

11

Application/X-Tar

Tar

Tar (4.3bsd)

12

Application/zip

Zip

WinZip

13

Audio/basic

AU SND

Sun/next sound file

14

Audio/MPEG

MPEG MP2

MPEG sound file

15

Audio/X-AIFF

Mid MIDI RMF

MIDI format

16

Audio/X-PN-RealAudio

Ram Ra

Real Audio voice

17

Audio/X-PN-RealAudio-plugin

Rpm

Real Audio plugin

18

Audio/X-WAV

Wav

Microsoft Windows sound

19

Image/CGM

CGM

Computer Graphics Metafile

20

Image/GIF

GIF

CompuServe GIF Image

21

Image/JPEG

Jpeg jpg jpe

JPEG Image

22

Image/PNG

PNG

PNG Image

Text/html

Text/plain txt

Text/XML

Text/JSON string

In addition, different browsers may obtain different types for the same file after uploading.

1. File Download:

The key code for file download is:

Response. setheader ("content-disposition", "attachment; filename =" + "test.rar"); // set the MIME type. response. setcontenttype ("application/X-tar"); response. setheader ("content_length", length); that is, you can set the attributes of httpservletresponse. One of the easiest ways to make mistakes in object downloading is through <a href = "test.txt"> download </a>. If you use a path like this: file: // C:/test/down.html, assuming that the previous line of code is included in download.html, you may be able to get it smoothly, if the HTML file (or JSP file) is on a Web server such as Tomcat, clicking this will not respond. When you view the source code, you will find that the link content changes:
Http: // localhost: 8080/file: // C:/test/down.html. I guess it may be like this: when the href value specified in the <A> label is a relative path, the Web Server adds the server root path before the relative path by default.
Is it a bit dizzy? It doesn't matter. You can understand this problem. When a file is downloaded, the file exists in a directory of the web server, or on the disk of the server. Therefore, we can access the file through Java file and related APIs in the servlet, because the servlet is executed on the server.. If the page presented to the client has such a link: <a href = "C:/test.txt"> download it! </A>
Can you get the test.txt file of the server C drive normally? Obviously not available. Href is resolved to http: // localhost: 8080/file: // C:/test.txt by the Web server and returned to the client.
How can I download an object? You cannot directly use the file path containing the drive letter to indicate href. However, the drive letter path can be used in servelt to construct a file object, load the file to the Web server memory, and write the file to the response stream to return it to the client, that is, it is implemented. The following is a code Demonstration: It mainly contains index. jsp, And the access path is/LoadFile's servelt (named LoadFile). The web. xml configuration servelt is omitted.

The LoadFile class is as follows:

import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class LoadFile extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)           throws IOException, ServletException {
       String filename = request.getParameter("filename");
       String path = request.getParameter("path");       OutputStream o = response.getOutputStream();       byte b[] = new byte[1024];       // the file to download.       File fileLoad = new File(path);       // the dialogbox of download file.       response.setHeader("Content-disposition", "attachment;filename="              + "test.txt");       // set the MIME type.       response.setContentType("text/html");       // get the file length.       long fileLength = fileLoad.length();       String length = String.valueOf(fileLength);       response.setHeader("Content_Length", length);       // download the file.       FileInputStream in = new FileInputStream(fileLoad);       int n = 0;       while ((n = in.read(b)) != -1) {           o.write(b, 0, n);       }    }     public void doPost(HttpServletRequest request, HttpServletResponse response)  throws IOException, ServletException {       doGet(request, response);    }}
That is, OK. 2. Although file uploading and downloading can be implemented through open-source components, it still takes a lot of effort to implement it on your own. File Upload is generally implemented by combining <form> form with <input type = "file">. Finally, get the input stream through requst in the server Servlet and write it to the server disk file. Although the principle is clear, can I write it directly like below?
Test. JSP <% @ page contenttype = "text/html; charset = gb2312" %> <HTML> <body> select the file to be uploaded: <br/> <form action = "Accept. JSP "method =" Post "enctype =" multipart/form-Data "> <input type =" file "name =" boy "size =" 38 "> <br/> <input type = "hidden" id = "TT" name = "T" value = "1"/> <input type = "Submit" id = "GG" name = "G" value = "Submit"/> </form> </body> 

Accept. JSP <% @ page contenttype = "text/html; charset = gb2312" %> <% @ page import = "Java. io. * "%> <HTML> <body> <% // tested. Description: Readline (byte [] B, int off, int Len) IN THE servletinputstream class) // The parameter byte [] B serves as a buffer. This method reads a row at a time, but if the size defined by byte [] B is smaller than the size of the row to be read, then // This method reads only the size specified by byte [] B. When the read operation is performed again, it continues the read that was not completed last time. Return Value: returns the actual number of bytes read, -1 is returned when the // of the Document Stream is read. Try {servletinputstream in = request. getinputstream (); file F = new file ("C: \ test", "a.txt"); fileoutputstream o = new fileoutputstream (f ); // if the value of byte B [] = is too short (if set to 2), the upload operation of the application will be affected, specifically, the document path and other related information cannot be parsed. byte B [] = new byte [2046]; int N; int I = 0; while (n = in. readline (B, 0, B. length ))! =-1) // The servletinputstream. Readline method reads data row by row. After reading the entire file, it returns-1. Generally, it returns the number of bytes read {I ++; system. out. println ("------" + I); O. write (B, 0, n);} o. close (); In. close ();} catch (ioexception e) {e. printstacktrace ();} Out. print ("File Uploaded"); %> <a href = "C: \ test \ a.txt"> View results </a> </body> 

Upload a test.txt file with three lines of Hello world !. Then open c: \ test \ a.txt with the following content:

--------------------------- 7db2611a404a4content-disposition: Form-data; name = "boy"; filename = "C: \ Users \ Xijiang \ Desktop \ test.txt" Content-Type: text/plainhello world! Hello world! Hello world! %7db2611a404a4content-disposition: Form-data; name = "T" 1 %7db2611a404a4content-disposition: Form-data; name = "G" Submit %7db2611a404a4 --

Obviously, we don't expect only three rows of Hello world !, Other form attribute values are added. Observe the content format of this file. We can see that,

-----------------------------7db2611a404a4
Is the field delimiter.
-----------------------------7db2611a404a4--
Is the Terminator.
<Input type = "file"> the corresponding value is:
-----------------------------7db2611a404a4Content-Disposition: form-data; name="boy"; filename="C:\Users\jxq\Desktop\test.txt"Content-Type: text/plainHello World!Hello World!Hello World!
That is, the first line is the content-disposition, name, and directory of the File Uploaded by the client, the second line is the file type to be uploaded, the third line is the blank line, and the next line is the file content.
Other attribute values of Form submission are expressed by content-Disposition: From-dat; name = xx.
Therefore, in order to obtain the real content of the uploaded file, we cannot simply read the input stream obtained from the request, which must be further parsed.

Reference link:

Http://blog.csdn.net/kanaka10/article/details/6526630

Http://zhangjunhd.blog.51cto.com/113473/19631

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.