Java File Upload-original servlet mode

Source: Internet
Author: User

Preface:

Do these several projects, also done several times file upload download, either copy project before the code, or Baidu, although made, but to learn the principle to get thorough or is necessary. Just went out to turn around to see if there is no rental, in Beijing to find a house is the heart feel the most uncomfortable time, no sense of belonging, rent is not cheap, RT, can not be ambitious, or down-to-earth 1.1-point learning technology bar, will eventually have a day, the wages would rise.

Java File Upload

Traditional file upload, without jquery plugin, is to use form form submission, Project used uploadify, can upload files asynchronously, the principle I did not study. Now say the traditional form form to upload files.

File Upload core:

    1. Declare a file field with <input type= "file"/>. Style such as file: _____ < browse;.
    2. You must submit the form using post.
    3. The type of the form must be set to Multipart/form-data. Is the setting that this form passes is not a key=value value. The byte code is passed.

To create a new Web project:

JSP form form: The default value for Enctype (encoding type) is application/x-www-form-urlencoded

Browser to view HTTP messages:

Main parameters:

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 The type returned by the receiving server, */* represents all.

Referer:http://localhost:8888/upload/from which website

accept-language:zh-cn,zh;q=0.8: The preferred language in the request response is Simplified Chinese

accept-encoding:gzip, deflate, BR supported compression formats

user-agent: mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/56.0.2924.87 safari/537.36 user Browser type

Host :localhost:8888 hosts Address

Connection:keep-alive message remains connected after sending

Cache-control: max-age=0 Cache

content-length: 41 41 bytes

To the file, the important parameters are:

Content-type: application/x-www-form-urlencoded

This parameter only has a POST request, the default is application/x-www-from-urlencoded, Content-type represents the body type, and the Get method has no body, because the parameter is in the URL.

In the servlet you can use the request object to fetch the Content-type:request.getheader ("Content-type"); The default value is application/ x-www-form-urlencoded,

if it is a GET request, the Request.getheader ("Content-type"); null.

is the HTTP header information when the GET request is:

 

file Upload, must be set enctype= " Multipart/form-data "

From form:

Upload a word:

HTTP message at this time : content-type:multipart/form-data; boundary=----Webkitformbou NDARYWYWQ3V1NEMO0BPFM.

The boundary=----webkitformboundary44gvxakosg3tk3or refers to the file upload delimiter.

Look at the requested message: Boundry=xxxxx identity file Start, also has the file header, said is the type of data uploaded, the first input is the text type, the second is binary, Content-type is Application/octet-stream represents Binary stream. Upload images, content-type:image/jpeg, upload text, Content-type:text/plain.

Reception of binary streams:

When the form type is post type, cut enctype= "Multipart/form-data", all data is uploaded to the server as a binary stream, so request.getparameter ("xxx") is always null, Only through Req.getinputstream (); Gets the body.

Upload a txt:

Servlet:

 PackageCom.lhy.upload;ImportJava.io.BufferedReader;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.io.OutputStream;ImportJava.io.PrintWriter;Importjavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/** *  * @authorAdministrator **/@WebServlet (Name= "Uploadservlet", urlpatterns= "/uploadservlet") Public classUploadservletextendshttpservlet{@Overrideprotected voiddoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {//this.dopost (req, resp);} @Overrideprotected voidDoPost (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {req.setcharacterencoding ("UTF-8"); String ContentType= Req.getheader ("Content-type"); System.out.println ("ContentType:" +ContentType); String name= Req.getparameter ("name"); SYSTEM.OUT.PRINTLN (name);//NULLInputStream is=Req.getinputstream (); //------WEBKITFORMBOUNDARYG0ULV7EVFQ1K2PBA//content-disposition:form-data; name= "image"; Filename= "Silent Night thinking. txt"//Content-type:text/plain//////------webkitformboundaryg0ulv7evfq1k2pba--BufferedReader br =NewBufferedReader (NewInputStreamReader (IS)); String Firstline= Br.readline ();//first line, delimiterString FileName =br.readline ();//content-disposition:form-data; name= "image"; Filename= "Jingyesi.txt"FileName = filename.substring (filename.lastindexof ("=") +2,filename.length ()-1);        Br.readline ();        Br.readline (); String Data=NULL; //gets the running path of the current projectString path = Getservletcontext (). Getrealpath ("/up"); PrintWriter PW=NewPrintWriter (path+ "/" +fileName);  while(data = Br.readline ())! =NULL){            if(Data.equals (firstline+ "--")){                 Break;//read the end of the file} pw.println (data);        } pw.flush ();        Pw.close ();               Is.close (); /*FileOutputStream fos = new FileOutputStream (path+ "/" + "B.doc");//byte[] B = new byte[1024];        int len = 0;        while (len = Is.read ())! =-1) {fos.write (len);        } fos.flush ();        Fos.close (); Is.close ();*/    }    }

In the project:

The example just reads TXT, and the other binaries need to be read using InputStream.

Java File Upload-original servlet mode

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.