Upload files on android

Source: Internet
Author: User

Android is very easy to upload files. It is the same as uploading in java. It is basically familiar with the operation output stream and input stream! Another important thing is to configure the content-type parameters! If all these are done, the upload will be simple! The following is an upload tool class I wrote:

Package com. spring. sky. image. upload. network;

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
* Activity upload interface
* @ Author Harry
* Email: huang8263901@qq.com
* QQ: 545614498
* MyName: Huang Mingming
*
*/
Public class UploadUtil {
Private static final String TAG = "uploadFile ";
Private static final int TIME_OUT = 10*1000; // timeout
Private static final String CHARSET = "UTF-8"; // sets the encoding.
/**
* Android uploads files to the server
* @ Param file the file to be uploaded
* @ Param RequestURL the requested rul
* @ Return the response content
*/
Public static String uploadFile (File file, String RequestURL)
{
String result = null;
String BOUNDARY = UUID. randomUUID (). toString (); // The boundary id is randomly generated.
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 is not allowed.
Conn. 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)
{
/**
* If 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 );
/**
* Important Notes:
* The value in name is the server. Only this key is required to obtain the corresponding file.
* Filename is the name of the file, which contains the suffix, for example, abc.png.
*/

Sb. append ("Content-Disposition: form-data; name = \" img \ "; filename = \" "+ file. getName () + "\" "+ LINE_END );
Sb. append ("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 [1, 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 ();
/**
* Response code 200 = successful
* When the response is successful, the response stream is obtained.
*/
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 StringBuffer ();
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;
}
}

The parameter is a File and a URL for the upload request. However, you must note that because network requests are required, do not forget that during the upload, add an access permission to the android client!

Another point is that you need to pay attention to this: I am working as a server-side javaEE. I found that during the upload process, if the file ID name is a java keyword, during the upload process, there will be many problems! Therefore, you may not use keywords!

The following is the Activity code:

Package com. spring. sky. image. upload;


Import java. io. File;

Import com. spring. sky. image. upload. network. UploadUtil;

Import android. app. Activity;
Import android. app. AlertDialog;
Import android. app. Dialog;
Import android. content. ContentResolver;
Import android. content. DialogInterface;
Import android. content. Intent;
Import android. database. Cursor;
Import android. graphics. Bitmap;
Import android. graphics. BitmapFactory;
Import android.net. Uri;
Import android. OS. Bundle;
Import android. provider. MediaStore;
Import android. util. Log;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. widget. Button;
Import android. widget. ImageView;
/**
* Activity upload interface
* @ Author Harry
* Email: huang8263901@qq.com
* QQ: 545614498
* MyName: Huang Mingming
*
*/
Public class MainActivity extends Activity implements OnClickListener {
Private static final String TAG = "uploadImage ";
Private static String requestURL = "http: // 192.168.1.14: 8080/SetBlobData/img! Up ";
Private Button selectImage, uploadImage;
Private ImageView imageView;

Private String picPath = null;

/** Called when the activity is first created .*/
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );

SelectImage = (Button) this. findViewById (R. id. selectImage );
UploadImage = (Button) this. findViewById (R. id. uploadImage );
SelectImage. setOnClickListener (this );
UploadImage. setOnClickListener (this );

ImageView = (ImageView) this. findViewById (R. id. imageView );


}

@ Override
Public void onClick (View v ){
Switch (v. getId ()){
Case R. id. selectImage:
/***
* Android built-in intent is called to filter image files and other
*/
Intent intent = new Intent ();
Intent. setType ("image /*");
Intent. setAction (Intent. ACTION_GET_CONTENT );
StartActivityForResult (intent, 1 );
Break;
Case R. id. uploadImage:
File file = new File (picPath );
If (file! = Null)
{
String request = UploadUtil. uploadFile (file, requestURL );
UploadImage. setText (request );
}
Break;
Default:
Break;
}
}

@ Override
Protected void onActivityResult (int requestCode, int resultCode, Intent data ){
If (resultCode = Activity. RESULT_ OK)
{
/**
* If the selected image is not empty, you can obtain the image
*/
Uri uri = data. getData ();
Log. e (TAG, "uri =" + uri );
Try {
String [] pojo = {MediaStore. Images. Media. DATA };

Cursor cursor = managedQuery (uri, pojo, null );
If (cursor! = Null)
{
ContentResolver cr = this. getContentResolver ();
Int colunm_index = cursor. getColumnIndexOrThrow (MediaStore. Images. Media. DATA );
Cursor. moveToFirst ();
String path = cursor. getString (colunm_index );
/***
* This judgment is mainly used for third-party software selection. For example, if a third-party file manager is used, the selected file may not be an image. In this case, we can determine the file suffix.
* Only images in image format can be used.
*/
If (path. endsWith ("jpg") | path. endsWith ("png "))
{
PicPath = path;
Bitmap bitmap = BitmapFactory. decodeStream (cr. openInputStream (uri ));
ImageView. setImageBitmap (bitmap );
} Else {alert ();}
} Else {alert ();}

} Catch (Exception e ){
}
}

Super. onActivityResult (requestCode, resultCode, data );
}

Private void alert ()
{
Dialog dialog = new AlertDialog. Builder (this)
. SetTitle ("prompt ")
. SetMessage ("the image you selected is not valid ")
. SetPositiveButton ("OK ",
New DialogInterface. OnClickListener (){
Public void onClick (DialogInterface dialog,
Int which ){
PicPath = null;
}
})
. Create ();
Dialog. show ();
}

}

Layout code:


Android: orientation = "vertical"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
>
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: text = "select image"
Android: id = "@ + id/selectImage"
/>
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: text = "uploading images"
Android: id = "@ + id/uploadImage"
/>
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: id = "@ + id/imageView"
/>

The above is all the code for android to upload images. If you want to upload other files, you can modify the filter conditions. At the same time, the file type must be consistent with the file type on the server, otherwise, the upload will fail!

If you still find any problems during use, contact me!

Learning lies in accumulation!

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.