Three ways to upload files-java

Source: Internet
Author: User
Tags spring mvc tutorial log4j

Foreword: Because of own responsibility project (jetty embedded launch of SPRINGMVC) need to implement file upload, and their own Java file upload this piece has not touched, and the Http protocol is more vague, so this time using a gradual way to learn the principle and practice of file upload. The blog is heavily practiced.


I. Introduction to the principle of HTTP protocol

HTTP is an object-oriented protocol belonging to the application layer , which is suitable for distributed hypermedia information System because of its simple and fast way. It was proposed in 1990, after several years of use and development, has been continuously improved and expanded. Currently used in the WWW is the sixth edition of Http/1.0, http/1.1 standardization work is in progress, and Http-ng (Next Generation of HTTP) has been proposed.

Simply put, is a communication specification based on the application layer: the two sides to communicate, everyone must abide by a specification, this specification is the HTTP protocol.

1. Features:

(1) Support client/server mode.

(2) Simple and fast: When a customer requests a service from the server, it simply transmits the request method and path. The request method commonly has, POST. Each method specifies a different type of contact between the customer and the server. Because the HTTP protocol is simple, the HTTP server's program size is small, so the communication speed is fast.

(3) Flexible: HTTP allows the transfer of any type of data object. The type being transmitted is marked by Content-type.

(4) No connection : The meaning of no connection is to limit the processing of only one request per connection. When the server finishes processing the customer's request and receives the customer's answer, the connection is disconnected. In this way, the transmission time can be saved.

(5) stateless : The HTTP protocol is a stateless protocol. Stateless means that the protocol has no memory capacity for transactional processing. A lack of state means that if the previous information is required for subsequent processing, it must be re-routed, which may cause the amount of data to be transferred per connection to increase. On the other hand, it responds faster when the server does not need the previous information.

Note : where (4) (5) is a common face test in the interview. Although the HTTP protocol (application layer) is non-connected, stateless, but its dependence on the TCP Protocol (transport layer) is often connected, stateful, and the TCP Protocol (Transport layer) is dependent on the IP Protocol (network layer).


Structure of the 2.HTTP message

(1) The request message is divided into 3 parts, the first part is called the requests line , the second part is called the HTTP header message header , the third part is the body body , the header and body have a blank line, structure such as


(2) The structure of the response message is basically the same as the structure of the request message.  Also divided into three parts, the first part is called the request line status lines , the second part is called the request header message body , the third part is the body text , between the header and the body also has a blank line, Structure such as



Here is the request message agency and Response messaging agency that uses fiddler capture requests for Baidu:


Because no form information is entered, so the message body of request is empty, you can find a login page to try.


First here, the HTTP protocol is rich in knowledge on the Internet and is no longer a good place to boil it.


Two. Three implementation of File upload

1.jsp/servlet implementing file Uploads

This is the most common and the simplest way

(1) jsp page to implement file upload

Import Java.io.file;import java.io.fileoutputstream;import Java.io.ioexception;import Java.io.InputStream;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import org.apache.log4j.logger;//@WebServlet (name = "Fileloadservlet", Urlpatterns = {"/fileload"}) public class Fileloadservlet extends HttpServlet {private static Logger Logger = Logger.getlogger (fileloadservlet.class);/** * */priv Ate static final long serialversionuid = 1302377908285976972L; @Overrideprotected void Service (HttpServletRequest Request, HttpServletResponse response) throws Servletexception, IOException {logger.info ("------------           Fileloadservlet------------"), if (Request.getcontentlength () > 0) {inputstream inputstream = null;           FileOutputStream outputstream = null; try {InputStream = Request.getinputstream ();//Spell time milliseconds for new files to prevent duplicate names long now = System.currenttimemillis (); FileFile = new file ("c:/", "file-" + Now + ". txt"); File.createnewfile (); outputstream = new FileOutputStream (File); byte temp[] = new Byte[1024];int size = -1;while ((size = Inputstream.read (temp))! =-1) {//read 1KB each time, until the end of the Outputstream.write (temp, 0, size);} Logger.info ("File load success.");} catch (IOException e) {logger.warn ("File load fail.", e); Request.getrequestdispatcher ("/fail.jsp"). Forward (Request, Response);} finally {outputstream.close (); Inputstream.close ();}} Request.getrequestdispatcher ("/succ.jsp"). Forward (request, response);}}

Fileuploadservlet configuration, recommend the use of servlet3.0 annotations more convenient way

  <servlet>    <servlet-name>FileLoadServlet</servlet-name>    <servlet-class> com.juxinli.servlet.fileloadservlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>FileLoadServlet</servlet-name>    <url-pattern>/fileload</url-pattern >  </servlet-mapping>

(3) Operation effect

Click on "Submit"



Page to file upload a successful page, then go to the C-disk to see, found a file: File-1433417127748.txt, this is just uploaded files



We opened it up and found something different from the original text.



Combined with the message structure of the preceding HTTP protocol, it is not difficult to find that the text is the "request message body" After removing the "header". So, if you want to get the text that is consistent with the uploaded file, you also need some string manipulation, which is left to everyone.

In addition, you can try a JSP page upload multiple files, there will be different wonderful oh O (∩_∩) O, not explained.


2. Simulate POST request/servlet implement file upload

Just now we are using JSP page to upload files, if the client is not WebApp project, obviously just that way some catch lapel see lining.

Here we change ideas, since the page by click can achieve file upload, why not through the HttpClient to simulate the browser to send the upload file request it. About HttpClient , you can get to know yourself.

(1) or this project, start the servlet service


(2) Fileloadclient of the analog request

Import Java.io.bufferedreader;import java.io.file;import java.io.inputstream;import java.io.InputStreamReader; Import Org.apache.commons.httpclient.httpclient;import Org.apache.commons.httpclient.httpstatus;import Org.apache.commons.httpclient.methods.postmethod;import Org.apache.commons.httpclient.methods.multipart.filepart;import Org.apache.commons.httpclient.methods.multipart.multipartrequestentity;import Org.apache.commons.httpclient.methods.multipart.part;import Org.apache.log4j.logger;public class FileLoadClient { private static Logger Logger = Logger.getlogger (fileloadclient.class);p ublic static string fileload (string url, file file {String BODY = ' {} '; if (url = = NULL | | url.equals (")) {return" argument not valid ";} if (!file.exists ()) {return "file name to upload does not exist";}        Postmethod Postmethod = new Postmethod (URL);            try {//Filepart: The class used to upload the file, file that is to be uploaded filepart fp = new Filepart ("file", file);            part[] parts = {FP}; For MIME-type requests, HttpClient is recommended for all MULitpartrequestentity for packaging multipartrequestentity mre = new multipartrequestentity (parts, Postmethod.getparams ())            ;                        Postmethod.setrequestentity (MRE);            HttpClient client = new HttpClient ();                        Because the file to be uploaded may be larger, set the maximum connection timeout at this time Client.gethttpconnectionmanager (). Getparams (). Setconnectiontimeout (50000);            int status = Client.executemethod (Postmethod);                if (status = = Httpstatus.sc_ok) {InputStream InputStream = Postmethod.getresponsebodyasstream ();                                BufferedReader br = new BufferedReader (new InputStreamReader (InputStream));                StringBuffer StringBuffer = new StringBuffer ();                String str = "";                while ((str = br.readline ()) = null) {stringbuffer.append (str);                            } BODY = stringbuffer.tostring (); } else {BODY = "fail";            }} catch (Exception e) {logger.warn ("Upload file exception", e);        } finally {//release connection postmethod.releaseconnection (); }return body;} public static void Main (string[] args) throws Exception {String BODY = fileload ("http://localhost:8080/jsp_ Upload-servlet/fileload ", New File (" C:/1111.txt ")); System.out.println (body);}}


(3) Run the Fileloadclient program in eclipse to send the request, running the result:

Printed: succ.jsp page for File upload success




Have you found anything that is similar to the results of the previous JSP page uploads? Yes, or remove the "request message body" after "header".


This method is also very simple, the fileuploadservlet is responsible for receiving the file is not changed, as long as the client to read the file into the stream, and then impersonate the request servlet line.


3. Analog POST request/controller (SPRINGMVC) for file upload

Finally to the third way, the main difficulty is to build the MAVEN+JETTY+SPRINGMVC environment, receive file service and impersonation request client and the above similar.


(1) The fileloadclient of the analog request is not changed

Import Java.io.bufferedreader;import java.io.file;import java.io.inputstream;import java.io.InputStreamReader; Import Org.apache.commons.httpclient.httpclient;import Org.apache.commons.httpclient.httpstatus;import Org.apache.commons.httpclient.methods.postmethod;import Org.apache.commons.httpclient.methods.multipart.filepart;import Org.apache.commons.httpclient.methods.multipart.multipartrequestentity;import Org.apache.commons.httpclient.methods.multipart.part;import Org.apache.log4j.logger;public class FileLoadClient { private static Logger Logger = Logger.getlogger (fileloadclient.class);p ublic static string fileload (string url, file file {String BODY = ' {} '; if (url = = NULL | | url.equals (")) {return" argument not valid ";} if (!file.exists ()) {return "file name to upload does not exist";}        Postmethod Postmethod = new Postmethod (URL);            try {//Filepart: The class used to upload the file, file that is to be uploaded filepart fp = new Filepart ("file", file);            part[] parts = {FP}; For MIME-type requests, HttpClient is recommended for all MULitpartrequestentity for packaging multipartrequestentity mre = new multipartrequestentity (parts, Postmethod.getparams ())            ;                        Postmethod.setrequestentity (MRE);            HttpClient client = new HttpClient ();                        Because the file to be uploaded may be larger, set the maximum connection timeout at this time Client.gethttpconnectionmanager (). Getparams (). Setconnectiontimeout (50000);            int status = Client.executemethod (Postmethod);                if (status = = Httpstatus.sc_ok) {InputStream InputStream = Postmethod.getresponsebodyasstream ();                                BufferedReader br = new BufferedReader (new InputStreamReader (InputStream));                StringBuffer StringBuffer = new StringBuffer ();                String str = "";                while ((str = br.readline ()) = null) {stringbuffer.append (str);                            } BODY = stringbuffer.tostring (); } else {BODY = "fail";            }} catch (Exception e) {logger.warn ("Upload file exception", e);        } finally {//release connection postmethod.releaseconnection (); }return body;} public static void Main (string[] args) throws Exception {String BODY = fileload ("Http://localhost:8080/fileupload/upload ", New File (" C:/1111.txt ")); System.out.println (body);}

(2) Servlet changed to controller in SPRINGMVC

Import Java.io.file;import java.io.fileoutputstream;import Java.io.ioexception;import Java.io.InputStream;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.log4j.logger;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.RequestMethod; @Controller @requestmapping ("/fileupload") public class Fileuploadservice {private Logger Logger = Logger.getlogger (Fileuploadservice.class); @RequestMapping (consumes = " Multipart/form-data ", value ="/hello ", method = requestmethod.get) public void Hello (httpservletrequest request, HttpServletResponse response) throws IOException {Response.getwriter (). Write ("Hello, jetty server start OK."); @RequestMapping (consumes = "Multipart/form-data", value = "/upload", method = requestmethod.post) public void UploadFile ( HttpServletRequest request, HttpServletResponse response) throws IOException {String ResUlt = ""; if (Request.getcontentlength () > 0) {inputstream inputstream = null;           FileOutputStream outputstream = null; try {InputStream = Request.getinputstream ();//Spell time milliseconds for new files to prevent duplicate names long now = System.currenttimemillis (); File File = new file ("c:/", "file-" + Now + ". txt"); File.createnewfile (); outputstream = new FileOutputStream (file); byte te mp[] = new Byte[1024];int size = -1;while ((size = Inputstream.read (temp))! =-1) {//read 1KB each time until the outputstream.write is read (temp , 0, size);} Logger.info ("File load success."); result = "File load success.";} catch (IOException e) {logger.warn ("file load fail.", e); result = "File load fail.";} finally {outputstream.close (); InputS Tream.close ();}} Response.getwriter (). write (result);}}

(3) Start the core code of jetty, the right mouse button can be launched in Eclipse, you can also make the project into a jar report start

Import Org.apache.log4j.logger;import Org.eclipse.jetty.server.connector;import org.eclipse.jetty.server.Server; Import Org.eclipse.jetty.server.serverconnector;import Org.eclipse.jetty.webapp.webappcontext;public class Launcher {private static Logger Logger = Logger.getlogger (launcher.class);p rivate static final int PORT = 8080;private STA Tic final String WEBAPP = "Src/main/webapp";p rivate static final String contextpath = "/";p rivate static final string DESC Riptor = "Src/main/webapp/web-inf/web.xml";/* * Create Jetty Server, specify its port, web directory, root directory, Web path * @param port * @param webapp * @par AM ContextPath * @param descriptor * @return Server */public static server createserver (int port, string webApp, String Co Ntextpath, String Descriptor) {Server server = new Server ();//Set the hook to close the jetty when the JVM exits//This allows the jetty to be started once throughout the functional test, Then let it automatically turn off Server.setstopatshutdown (true) when the JVM exits; Serverconnector connector = new Serverconnector (server); Connector.setport (port); Fix a problem with Windows recurring startup jetty not reporting port conflicts//Windows + Sun C under WindowsOnnector implementation of the problem, reuseaddress=true when the same port repeatedly started jetty will not error//So must be set to False, the price is if the last exit is not clean (such as a time_wait), will cause the new jetty can not start, However, the balance should be set to Falseconnector.setreuseaddress (false); Server.setconnectors (new Connector[]{connector}); Webappcontext webcontext = new Webappcontext (webApp, ContextPath); Webcontext.setdescriptor (descriptor);// Set the location of the webApp webcontext.setresourcebase (WEBAPP); Webcontext.setclassloader (Thread.CurrentThread (). Getcontextclassloader ()); Server.sethandler (webcontext); return server;} /** * Start Jetty service * */public void Startjetty () {final Server server = Launcher.createserver (PORT, WEBAPP, ContextPath, DESC Riptor); try {server.start (); Server.join ();} catch (Exception e) {Logger.warn ("Start jetty Server failed", e); System.exit (-1);}} public static void Main (string[] args) {(new Launcher ()). Startjetty ();//jetty startup test url//http://localhost:8080/ Fileupload/hello}}


SPRINGMVC configuration is not affixed, we can download the source under the view.


(4) Operation effect

After running Launcher, you can access Http://localhost:8080/fileupload/hello to see if Jetty+springmvc startup is ok



Log printed after running fileloadclient:



Description File Upload Successful




Attached source Download:

Jsp_upload-servlet Project: (1). Jsp/servlet implement file Upload (2). Simulate POST request/servlet implement file upload

JETTY_UPLOAD-SPRINGMVC Project: (3). Analog POST Request/controller (SPRINGMVC) for file upload

Csdn

Three ways to upload files-java


GitHub

Https://github.com/leonzm/jsp_upload-servlet.git
Https://github.com/leonzm/jetty_upload-springmvc.git


Time is more hasty, there may be wrong or imperfect place, we can put forward to study together.


References & References:

An analysis of HTTP protocol
Http://www.cnblogs.com/gpcuster/archive/2009/05/25/1488749.html

HTTP protocol Detailed
http://blog.csdn.net/gueter/article/details/1524447

HTTP protocol Detailed
http://kb.cnblogs.com/page/130970/

HttpClient Learning and Finishing
Http://www.cnblogs.com/ITtangtang/p/3968093.html


The difference between TCP/IP, Http, and socket
Http://jingyan.baidu.com/article/08b6a591e07ecc14a80922f1.html


Spring MVC Tutorial, Quick Start, in-depth analysis
http://yinny.iteye.com/blog/1926799

Jetty Boot and embedded boot
http://yinny.iteye.com/blog/1926799

Start Jetty Mode
http://hbiao68.iteye.com/blog/2111007

Jetty More Practical Boot program
Http://www.xuebuyuan.com/1400368.html



Three ways to upload files-java

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.