Upload Android files

Source: Internet
Author: User

Due to work needs, GPS (2) has not been completed yet. Today we are finished. To implement the content uploaded to a file, Android can use Socket to upload a file, you can also simulate the Web upload. However, if you use the first upload method, you must use TCP to ensure that the system is easy to generate and die, or wait for a long time. If you use UDP for upload, this can easily cause data loss. Therefore, you have selected Web to upload data. Using Web to upload data is a simulated Http Post upload data. Of course, the Post upload data class, I found it on the Internet. Although there are many ways, none of them feel that I am using it. So I made some modifications based on the principle and so on, which is a reference. This class is used to complete the file and commendation upload service.
The Code is as follows:
File and form upload class:
 
Code
Package com. UpLoadFileTest;

Import java. io. BufferedReader;
Import java. io. DataOutputStream;
Import java. io. File;
Import java. io. FileInputStream;
Import java. io. IOException;
Import java. io. InputStreamReader;

Import java. io. InputStream;
Import java.net. HttpURLConnection;
Import java.net. URL;

Import java. util. Map;

Public class PostFile {
// Upload code. The first parameter is the URL to be used, the second parameter is the form content, and the third parameter is the file to be uploaded. You can upload multiple files, this depends on your needs.
Public static String post (String actionUrl, Map <String, String> params,
Map <String, File> files) throws IOException {

String BOUNDARY = java. util. UUID. randomUUID (). toString ();
String PREFIX = "--", LINEND = "\ r \ n ";
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 );
Conn. setDoInput (true); // allow input
Conn. setDoOutput (true); // allow output
Conn. setUseCaches (false );
Conn. setRequestMethod ("POST"); // Post method
Conn. setRequestProperty ("connection", "keep-alive ");
Conn. setRequestProperty ("Charsert", "UTF-8 ");

Conn. setRequestProperty ("Content-Type", MULTIPART_FROM_DATA
+ "; Boundary =" + BOUNDARY );


// Set parameters of the text type first
StringBuilder sb = new StringBuilder ();
For (Map. Entry <String, String> entry: params. entrySet ()){
Sb. append (PREFIX );
Sb. append (BOUNDARY );
Sb. append (LINEND );
Sb. append ("Content-Disposition: form-data; name = \""
+ Entry. getKey () + "\" "+ LINEND );
Sb. append ("Content-Type: text/plain; charset =" + CHARSET + LINEND );
Sb. append ("Content-Transfer-Encoding: 8bit" + LINEND );
Sb. append (LINEND );
Sb. append (entry. getValue ());
Sb. append (LINEND );
}

DataOutputStream outStream = new DataOutputStream (conn
. GetOutputStream ());
OutStream. write (sb. toString (). getBytes ());
// Send file data
If (files! = Null)
For (Map. Entry <String, File> file: files. entrySet ()){
StringBuilder sb1 = new StringBuilder ();
Sb1.append (PREFIX );
Sb1.append (BOUNDARY );
Sb1.append (LINEND );
Sb1
. Append ("Content-Disposition: form-data; name = \" file \ "; filename = \""
+ File. getKey () + "\" "+ LINEND );
Sb1.append ("Content-Type: application/octet-stream; charset ="
+ CHARSET + LINEND );
Sb1.append (LINEND );
OutStream. write (sb1.toString (). getBytes ());

InputStream is = new FileInputStream (file. getValue ());
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 ());
}

// Request end mark
Byte [] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND). getBytes ();
OutStream. write (end_data );
OutStream. flush ();
// Get the response code
Int res = conn. getResponseCode ();
InputStream in = conn. getInputStream ();
InputStreamReader isReader = new InputStreamReader (in );

BufferedReader bufReader = new BufferedReader (isReader );

String line = null;
String data = "OK ";
While (line = bufReader. readLine () = null)
Data + = line;

If (res = 200 ){
Int ch;
StringBuilder sb2 = new StringBuilder ();
While (ch = in. read ())! =-1 ){
Sb2.append (char) ch );
}
}
OutStream. close ();
Conn. disconnect ();
Return in. toString ();
}

}
Copy code
If you want to write (upload) data, you can use out. write or out. wrtebyte (content) to convert the data.
This can be based on personal needs, with a waiting record, etc. If you want to add a waiting record, you need to use the message sending method. This is what I think, if you are interested in other methods, you can add them on your own! I will not add any more here. If it is added, a download progress prompt will be added to the download.
 
 
The implementation is as follows:
 
Code

Button btn1;

EditText view1;
EditText text1;
String SDPath = "/sdcard /";

/** Called when the activity is first created .*/
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
View1 = (EditText) findViewById (R. id. view1 );
Text1 = (EditText) findViewById (R. id. edit1 );
Btn1 = (Button) findViewById (R. id. btn1 );
Btn1.setOnClickListener (new View. OnClickListener (){

@ Override
Public void onClick (View v ){
// TODO Auto-generated method stub
GetFile ();
Try {
String name = URLEncoder. encode (text1.getText (). toString (), "UTF-8 ");
Map <String, String> params = new HashMap <String, String> ();
Params. put ("NAME", name );
Map <String, File> files = new HashMap <String, File> ();
Files. put (getFile (), new File ("/sdcard/" + getFile ()));
View1.setText (PostFile. post ("http://wdsl.recordinfo.tk/default.aspx", params, files ));
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}

}
});
}

String getFile (){
File file = new File (SDPath );
File [] files = file. listFiles (new fileFilter ());
String filename = "";
For (File file1: files ){
Filename = file1.getName ();
}

Toast. makeText (this, filename, Toast. LENGTH_LONG). show ();
Return filename;
}

Class fileFilter implements FilenameFilter {

@ Override
Public boolean accept (File dir, String filename ){
// TODO Auto-generated method stub
Return filename. endsWith (". gif ");
}

}
Copy code
 
These are just the content in the class, and I only took a photo on the SD card, so I put a picture on the card, so I did not list the processed, if you are interested, you can add it on your own, because I mainly implement this function and practice this function!

 

From Binbin's blog

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.