[Experience record] Android uploads files to the server

Source: Internet
Author: User

In Android, file upload is actually very simple. It is the same as in java. Basically, it is familiar with the operation output stream and input stream! Another important thing is to configure some parameters of content-type! If all of these are done, the upload will be simple. The following is a tool class for uploading: 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 class ** @ author spring sky Email: vipa1 888@163.com QQ: 840950105 MyName: Shi mingzheng */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 "; // set the encoding/*** Android uploads stationery to the server ** @ param file * file to be uploaded * @ param RequestURL * Requested rul * @ return returned 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 = \" 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 [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 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. the printStackTrace () ;}return result ;}} parameter is a File and a URL to be uploaded. However, note that because network requests are used, therefore, do not forget to add a network access permission to the android client during upload! 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. graph Ics. 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 spring sky Email: vipa1888@163.com QQ: 840950105 MyName: Shi mingzheng **/public class MainActivity extends Activity implement S 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:/***** this is the built-in android intent called to filter image files. It can also filter 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) {/*** when the selected image is not empty, obtain the image path */Uri uri = data. getData (); Log. e (TAG, "uri =" + uri); try {String [] pojo = {MediaStore. images. media. DATA}; Cur Sor 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 you use a third-party file manager, the file you selected is not necessarily an image. * In this case, we can determine the file suffix. if it is an image format, then we can */if (path. endsWith ("jpg") | path. endsWith ("png") {picPath = path; Bitmap bitmap = BitmapFacto Ry. decodeStream (cr. openInputStream (uri); imageView. setImageBitmap (bitmap);} 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 (Di AlogInterface dialog, int which) {picPath = null ;}}). create (); dialog. show () ;}} layout code: <? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: orientation = "vertical" android: layout_width = "fill_parent" android: layout_height = "fill_parent"> <Button android: id = "@ + id/selectImage" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: text = "select image"/> <Button android: id = "@ + id/uploadImage" android: layout_width = "fill_parent" android: layout_heig Ht = "wrap_content" android: text = "Upload image"/> <ImageView android: id = "@ + id/imageView" android: layout_width = "wrap_content" android: layout_height = "wrap_content"/> </LinearLayout> the above is all the code for android to upload images. 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!

 

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.