Android uploads files to Web server via HTTP

Source: Internet
Author: User
Tags response code
The code is as follows Copy Code

<?php

If you have an upload file, you receive

if ($_files) {

$target _path = $target _path. basename ($_files[' file1 '] [' name ']);

try{if (move_uploaded_file ($_files[' file1 '] [' tmp_name '], $target _path)) {

echo "The file".  basename ($_files[' file1 '] [' name ']). "has been uploaded";

}

catch (Exception $e) {

echo $e->getmessage (); }

}

?>

Android Code:

Package com.nbcio.baishicha.test;
Import Java.io.DataOutputStream;

Import Java.io.FileInputStream;

Import java.io.IOException;

Import Java.io.InputStream;

Import java.net.HttpURLConnection;

Import Java.net.URL;

Import android.app.Activity;

Import android.content.Intent;

Import Android.os.Bundle;

Import Android.widget.Toast;


public class Test extends activity {

/*

* Variable declaration newName: The name of the file on the server after uploading

*

* UploadFile: File path to upload actionurl: server corresponding program path

*/

Private String NewName = "";

Private String UploadFile = "";

Private String ActionURL = "http://www.111cn.net/index.php";//define your upload path here


@Override

public void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate);
Intent Intent = This.getintent ();

Bundle Bundle = Intent.getextras ();

NewName = bundle.getstring ("FileName");

UploadFile = NewName;
try {

String OK = post (ActionURL, newName);

Toast.maketext (This, "ok!", Toast.length_long). Show ();

Finish ();


catch (IOException e) {

//

TODO auto-generated Catch block

E.printstacktrace ();

}


}


* * Upload file to the server method * *

/**

*

* @param actionurl

* @param params

* @param files

* @return

* @throws IOException

*/

public static string post (string ActionURL, String FileName)

Throws IOException {


String boundary = Java.util.UUID.randomUUID (). toString ();

String PREFIX = "--", Linend = "RN";

String multipart_from_data = "Multipart/form-data";

String CHARSET = "UTF-8";


URL uri = new URL (actionurl);

HttpURLConnection conn = (httpurlconnection) uri.openconnection ();

Conn.setreadtimeout (5 * 1000);

The maximum length of time to cache

Conn.setdoinput (TRUE);//Allow input

Conn.setdooutput (TRUE);//Allow output

Conn.setusecaches (FALSE); Caching is not allowed

Conn.setrequestmethod ("POST");

Conn.setrequestproperty ("Connection", "keep-alive");

Conn.setrequestproperty ("Charsert", "UTF-8");

Conn.setrequestproperty ("Content-type", Multipart_from_data

+ "; boundary=" + boundary);


DataOutputStream OutStream = new DataOutputStream (

Conn.getoutputstream ());


Send file Data

if (FileName!= "") {


StringBuilder sb1 = new StringBuilder ();

Sb1.append (PREFIX);

Sb1.append (boundary);

Sb1.append (Linend);

Sb1.append ("Content-disposition:form-data; Name= "File1"; Filename= ""

+ FileName + "" "+ linend);

Sb1.append ("Content-type:application/octet-stream; Charset= "

+ CHARSET + linend);

Sb1.append (Linend);

Outstream.write (Sb1.tostring (). GetBytes ());


InputStream is = new FileInputStream (FileName);

byte[] buffer = new byte[1024];

int len = 0;

while (len = is.read (buffer))!=-1) {

Outstream.write (buffer, 0, Len);

}


Is.close ();

Outstream.write (Linend.getbytes ());


}


End of Request flag

Byte[] End_data = (PREFIX + boundary + PREFIX + linend). GetBytes ();

Outstream.write (End_data);

Outstream.flush ();


Get Response code

int res = Conn.getresponsecode ();

InputStream in = null;

if (res = = 200) {

in = Conn.getinputstream ();

int ch;

StringBuilder SB2 = new StringBuilder ();

while (ch = in.read ())!=-1) {

Sb2.append ((char) ch);

}

}

return in = = null? Null:in.toString ();

}

}

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.