Android uploads the mobile phone image to the server and saves it on the server.

Source: Internet
Author: User
Server servlet code publicvoid dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {string temp = request. getsession (). getservletcontext (). getrealpath ("/") + "Temp"; // temporary directory system. out. println ("temp =" + temp); string loadpath = request. getsession (). getservletcontext (). getrealpath ("/") + "image"; // upload the file storage directory system. out. println ("loadpath =" + loadpath); diskfileupload Fu = New diskfileupload (); Fu. setsizemax (1*1024*1024); // set the size of the file to be uploaded. Unit: byte Fu. setsizethreshold (4096); // you can specify a maximum of data that can be stored in the memory. The unit is byte Fu. setrepositorypath (temp); // if the file size exceeds the value of getsizethreshold (), the data is stored in the directory of the hard disk. // The Int Index = 0; List fileitems = NULL; try {fileitems = Fu. parserequest (request); system. out. println ("fileitems =" + fileitems);} catch (exception e) {e. printstacktrace ();} iterator iter = fileit EMS. iterator (); // process each uploaded file in sequence while (ITER. hasnext () {fileitem item = (fileitem) ITER. next (); // ignore all other form information not in the file field if (! Item. isformfield () {string name = item. getname (); // get the upload file name, including path name = Name. substring (name. lastindexof ("\") + 1); // extract the file name from the full path long size = item. getsize (); If (name = NULL | Name. equals ("") & size = 0) continue; int point = Name. indexof (". "); name = (new date ()). gettime () + name. substring (point, name. length () + index; index ++; file fnew = new file (loadpath, name); try {item. write (fnew);} catch (exception e ){ // Todo auto-generated Catch Block E. printstacktrace () ;}} else // retrieve all form information not in the file field {string fieldvalue = item. getstring (); // if it contains Chinese characters, it should be written to :( convert to UTF-8 encoding) // string fieldvalue = new string (item. getstring (). getbytes (), "UTF-8") ;}} string text1 = "11"; response. sendredirect ("result. JSP? Text1 = "+ text1);} publicclass photoupload extends activity {private string newname =" image.jpg "; private string uploadfile ="/sdcard/image. jpg "; private string actionurl =" http: // 192.168.0.71: 8086/helloword/myform "; private textview mtext1; private textview mtext2; private button mbutton; @ override publicvoid oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. photo_upload); mtext1 = (textview) findviewbyid (R. id. mytext2); // "file path: \ n" + mtext1.settext (uploadfile); mtext2 = (textview) findviewbyid (R. id. mytext3); // "Upload URL: \ n" + mtext2.settext (actionurl);/* set the onclick event processing of mbutton */mbutton = (button) findviewbyid (R. id. mybutton); mbutton. setonclicklistener (new view. onclicklistener () {publicvoid onclick (view v) {uploadfile () ;}}) ;}/ * upload the file to the server Method */privatevoid uploadfile () {string end = "\ r \ n"; string twohyphens = "--"; string boundary = "*****"; try {URL url = new URL (actionurl); httpurlconnection con = (httpurlconnection) URL. openconnection ();/* allow input and output without using cache */con. setdoinput (true); con. setdooutput (true); con. setusecaches (false);/* set the transfer method = post */con. setrequestmethod ("Post");/* setrequestproperty */con. setrequestpropert Y ("connection", "keep-alive"); con. setrequestproperty ("charset", "UTF-8"); con. setrequestproperty ("Content-Type", "multipart/form-data; boundary =" + boundary);/* Set dataoutputstream */dataoutputstream DS = new dataoutputstream (con. getoutputstream (); DS. writebytes (twohyphens + boundary + end); DS. writebytes ("content-Disposition: Form-data;" + "name = \" file1 \ "; filename = \" "+ newname +" \ "" + end); DS. WRI Tebytes (end);/* Get the fileinputstream */fileinputstream fstream = new fileinputstream (uploadfile);/* Set 1024 bytes */INT buffersize = 1024 for each write; byte [] buffer = newbyte [buffersize]; int length =-1;/* read data from the file to the buffer */while (length = fstream. read (buffer ))! =-1) {/* write data to dataoutputstream */Ds. write (buffer, 0, length);} Ds. writebytes (end); DS. writebytes (twohyphens + boundary + twohyphens + end);/* close streams */fstream. close (); DS. flush ();/* Get Response content */inputstream is = con. getinputstream (); int ch; stringbuffer B = new stringbuffer (); While (CH = is. read ())! =-1) {B. append (char) CH);}/* display response in dialog */showdialog ("uploaded successfully" + B. tostring (). trim ();/* close dataoutputstream */Ds. close () ;}catch (exception e) {showdialog ("Upload Failed" + E) ;}/ * display dialog's Method */privatevoid showdialog (string mess) {New alertdialog. builder (photoupload. this ). settitle ("message "). setmessage (MESS ). setnegativebutton ("OK", new dialoginterface. onclicklistener () {publicvoid onclick (dialoginterface dialog, int which ){}}). show ();}}
Related Article

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.