Order
The dog, the teacher needs me to implement upload images to the remote file server, said to be load-balanced, resource synchronization, data Security ... Balabala, the reason can say a large basket of ...
As aged respected four good youth, after all, the teacher took me so long, he said what is what ... So do ...
1. Process
All kinds of ask Niang, look at the blog, visit the forum ... HttpClient, HttpURLConnection, FTP, SFTP ... Okay, all right? Various network transport protocols have been tried once and found themselves back to the original point ...
The reason of oneself mentally retarded, lazy ... Just want to copy the code on the Internet, direct use, but there is no good analysis ...
2, confusedbusy for one weeks, the teacher has been urging, but there has been no progress, always want to have an old driver to take me to fly much better, but the more so think, the more I have no confidence, the bitter lesson ... 3. HopeWell, you can't count on an old driver, or on your own. Use Google, on GitHub, read the documentation carefully ... Chat with her sister, Sister encouraged me, and again have confidence in themselves ...slowly, I have a clue, as the villain in the United States 3, said, "As long as there is experience and patience, anything can be done ..."The last reason to choose the HTTP protocol is that the HTTP protocol is probably the most widely used and most important protocol on the Internet now, and more and more Java applications need to access network resources directly through the HTTP protocol. while the basic functionality of accessing the HTTP protocol has been provided in the JDK's java.net package, the JDK library itself provides a lack of functionality and flexibility for most applications. HttpClient is used to provide efficient, up-to-date, feature-rich client programming toolkits that support the HTTP protocol, and it supports the latest versions and recommendations of the HTTP protocol. 4. Code
local server 192:ckeditoruploadaction
Postmethod filepost = new Postmethod (URL_STR); HttpClient client = new HttpClient (); String dirName = GetUserInfo (). GetUserName (); try { //The following method can simulate the page parameter submission part[] parts = {New Filepart (dirname+ '-' +truename, ToFile)}; Filepost.setrequestentity (New multipartrequestentity (Parts, Filepost.getparams ())); Client.gethttpconnectionmanager (). Getparams (). Setconnectiontimeout (in); int status = Client.executemethod (FilePost); if (status = = Httpstatus.sc_ok) { System.out.println ("Upload succeeded"); } else { System.out.println ("Upload failed"); } } catch (Exception ex) { ex.printstacktrace (); } finally { filepost.releaseconnection (); }
Remote server 192:uploadfileservlet
Package Com.servlet;import Java.io.file;import Java.io.ioexception;import java.io.UnsupportedEncodingException; Import Java.util.iterator;import Java.util.list;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.commons.fileupload.fileitem;import Org.apache.commons.fileupload.fileuploadexception;import Org.apache.commons.fileupload.disk.diskfileitemfactory;import org.apache.commons.fileupload.servlet.servletfileupload;/** * Servlet Implementation class Uploadfileservlet */@ Webservlet ("/uploadfileservlet") public class Uploadfileservlet extends HttpServlet {private static final long Serialversionuid = 1L; /** * @see httpservlet#httpservlet () */public Uploadfileservlet () {super (); TODO auto-generated Constructor stub}/** * @see Httpservlet#doget (httpservletrequest request,HttpServletResponse response) */protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {//TODO auto-generated Method Stubresponse.getwriter (). Append ("Served at:"). Append ( Request.getcontextpath ()); try {processupload (request,response);} catch (Fileuploadexception e) {//TODO Auto-generated catch Blocke.printstacktrace ();}} /** * @see Httpservlet#dopost (httpservletrequest request, httpservletresponse response) */protected void DoPost ( HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {//TODO auto-generated Method Stubdoget (Request, response);} String uploadpath= "c:\\test\\";p rivate static String Uploadpath = "c:\\apache-tomcat-8.0.28-windows-x64\\webapps\\ Uploads\\ ";p ublic void Processupload (HttpServletRequest request, httpservletresponse response) throws fileuploadexception{file UploadFile = new file (Uploadpath); if (!uploadfile.exists ()) {UPLOADFILE.MKDIRS (); } System.out.println ("Come on, baby ....."); try {request.setcharacterencoding ("Utf-8"),} catch (Unsupportedencodingexception E1) {//TODO auto-generated catch Blocke1.printstacktrace ();} Response.setcharacterencoding ("Utf-8"); Detects if there is an upload file that is Boolean ismultipart = servletfileupload.ismultipartcontent (request); if (Ismultipart) {Diskfileitemfactory factory = new Diskfileitemfactory (); Specifies the size of the cache data in memory, in bytes, which is set to 1Mb factory.setsizethreshold (1024*1024); Sets the data stored in the hard disk's directory factory.setrepository ("C:\\Temp") once the file size exceeds the value of Getsizethreshold (); Create a new file upload handler servletfileupload upload = new Servletfileupload (factory); Specifies the maximum size of a single upload file, in bytes, set to 50Mb Upload.setfilesizemax (50 * 1024 * 1024); MeansThe total size, in bytes, of 50Mb Upload.setsizemax (50 * 1024 * 1024) is set to upload multiple files at once. Upload.setheaderencoding ("UTF-8"); list<fileitem> items = upload.parserequest (request); if (items!=null) {//Parse form item iterator<fileitem> ITER = Items.iterator (); while (Iter.hasnext ()) {Fileitem item = Iter.next (); System.out.println ("Item ...." +item); System.out.println ("Item.getfilename () ..." +item.getfieldname ()); If it is a normal form attribute if (Item.isformfield ()) {///equals the name attribute of input <input type= "Te XT "Name=" content "> String name = Item.getfieldname (); The Value property of input String value = item.getstring (); System.out.println ("attribute:" + name + "attribute value:" + value); }//If uploading a file else {//property name String fieldName = Item.getfieldname (); String[] Strarray=fieldname.split ("-"); String Newuploadpath =uploadpath+strarray[0]; File DirName = new file (Newuploadpath); if (!dirname.exists ()) {dirname.mkdirs (); }//Upload file path String fileName = Item.getname (); filename = filename.substring (Filename.lastindexof ("/") + 1);//Get the file name of the uploaded files try {item.write (new File (Newuploadpath, strarray[1])); } catch (Exception e) {e.printstacktrace (); } } } } } Response.AddHeader ("token", "Hello"); }}
PS: A lot of online no server code, too pit, server attention needs two jar files, Commons-fileupload-1.3.1.jar and Commons-io-2.5.jarlast required jar, package download: Link: http://download.csdn.net/detail/sage_wang/9515110
Original: Sh+ckeditor use httpclient to implement file upload
Using HttpClient to upload files under Ssh+ckeditor