Upload files on Android

Source: Internet
Author: User

1. Android:

1.1 layout file:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/hello" />         <TextView        android:id="@+id/mTextView1"         android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/hello" />      <TextView        android:id="@+id/mTextView2"         android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/hello" />              <Button        android:id="@+id/mButton1"         android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/hello" />     </LinearLayout>

1.2 activity:

Package Org. yang. android. upload; import Java. io. file; import android. app. activity; import android. OS. bundle; import android. OS. environment; import android. view. view; import android. widget. button; import android. widget. textview; public class androiduploadfileactivity extends activity {private string newname = "linux.jpg"; // path of the local file to be uploaded: Private string uploadfile = environment. getexternalstoragedirectory () + "/IM Age/psb.jpg "; // Private string actionurl =" http: // 172.17.151.54: 8090/finalproject/JSP/androiduploadfile "; private textview mtextview1; private textview mtextview2; private button mbutton1; file = new file (uploadfile); @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); If (file. exists () {system. out. println ("file is Exists !! ");} Else {system. Out. println (" file is not exists !! ");} System. out. println ("uploadfile is" + uploadfile); mtextview1 = (textview) findviewbyid (R. id. mtextview1); mtextview1.settext ("filepath:/N" + uploadfile); mtextview2 = (textview) findviewbyid (R. id. mtextview2); mtextview2.settext ("uploadpath:/N" + actionurl);/* set the onclick event processing of mbutton */mbutton1 = (button) findviewbyid (R. id. mbutton1); mbutton1.setonclicklistener (new view. onclicklistener () {public void onclick (view v) {fileuplaodutil. uploadfile (androiduploadfileactivity. this. file, actionurl );}});}}

1.2 fileuploadutil. Java file:

Package Org. yang. android. upload; import Java. io. dataoutputstream; import Java. io. file; import Java. io. fileinputstream; import Java. io. ioexception; import Java. io. inputstream; import java.net. httpurlconnection; import java.net. malformedurlexception; import java.net. URL; import Java. util. UUID; import android. util. log;/*** upload tool class ** @ author spring sky Email: vipa1888@163.com QQ: 840950105 myname: Shi mingzheng */Public C Lass fileuplaodutil {Private Static final string tag = "uploadfile"; Private Static final int time_out = 10*1000; // time-out Private Static final string charset = "UTF-8 "; // set the encoding/*** Android uploads a file to the server ** @ Param file * the file to be uploaded * @ Param requesturl * the requested rul * @ return returns the response content */ public static string uploadfile (File file, string requesturl) {string result = NULL; string boundary = UUID. randomuuid (). tostring (); // String prefix = "--", line_end = "\ r \ n"; string content_type = "multipart/form-Data "; // content type try {URL url = new URL (requesturl); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setreadtimeout (time_out); Conn. setconnecttimeout (time_out); Conn. setdoinput (true); // allow the input stream Conn. setdooutput (true); // allow the output stream Conn. setusecaches (false); // cache Conn is not allowed. setrequestmethod ("Post "); // Request Method Conn. setrequestproperty ("charset", charset); // sets the encoding Conn. setrequestproperty ("connection", "keep-alive"); Conn. setrequestproperty ("Content-Type", content_type + "; boundary =" + boundary); If (file! = NULL) {/*** when the file is not empty, package the file and upload it */dataoutputstream dos = new dataoutputstream (Conn. getoutputstream (); stringbuffer sb = new stringbuffer (); sb. append (prefix); sb. append (Boundary); sb. append (line_end);/*** note: the value in name is that the server requires the key. Only this key can be used to obtain the corresponding file * filename is the file name, contains the suffix, for example, abc.png */SB. append ("content-Disposition: Form-data; name = \" uploaded \ "; filename = \" "+ file. getname () + "\" "+ line_end); sb. appen D ("Content-Type: Application/octet-stream; charset =" + charset + line_end); sb. append (line_end); dos. write (sb. tostring (). getbytes (); inputstream is = new fileinputstream (File); byte [] bytes = new byte [1024]; int Len = 0; while (LEN = is. read (bytes ))! =-1) {dos. write (bytes, 0, Len);} is. close (); dos. write (line_end.getbytes (); byte [] end_data = (prefix + boundary + prefix + line_end ). getbytes (); dos. write (end_data); dos. flush ();/*** get response code 200 = success when the response is successful, get the response stream */INT res = Conn. getresponsecode (); log. E (TAG, "response code:" + Res); // If (RES = 200) // {log. E (TAG, "request success"); inputstream input = Conn. getinputstream (); stringbuffer SB1 = new stringbuff Er (); int SS; while (Ss = input. Read ())! =-1) {sb1.append (char) SS);} result = sb1.tostring (); log. E (TAG, "Result:" + result); //} // else {// log. E (TAG, "request error"); // }}} catch (malformedurlexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();} return result ;}}

2. server side:

package org.android.action.file;import java.io.File;import org.android.tool.UploadFileTool;import org.apache.commons.io.FileUtils;import com.opensymphony.xwork2.ActionSupport;public class UploadFileAction extends ActionSupport{private static final long serialVersionUID = 1L;private int result;private String msg;private String uploadedFileName;private File uploaded;public int getResult(){return result;}public void setResult(int result){this.result = result;}public String getMsg(){return msg;}public void setMsg(String msg){this.msg = msg;}public String getUploadedFileName(){return uploadedFileName;}public void setUploadedFileName(String uploadedFileName){this.uploadedFileName = uploadedFileName;}public File getUploaded(){return uploaded;}public void setUploaded(File uploaded){this.uploaded = uploaded;}// --------------------------------------Method--------------------------------------------------//public void receiveFile() throws Exception{File f = new File("e:\\" + getUploadedFileName());System.out.println("e:\\" + getUploadedFileName());FileUtils.copyFile(getUploaded(), f);System.out.println("UPLOAD SUCCESS!!!!!! + Java Web");}}
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.