Android-----based on xutils photo upload client and server-side implementation

Source: Internet
Author: User

Presumably everyone in the Android more or less used the xutils framework, today we through him to achieve a photo upload demo, hope to be helpful to everyone, The next article from the source point of view to analyze the xutils of the httputils is how a process of implementation;

On first execution:


client implementations:

First look at the layout file:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: Context= ". Mainactivity "> <linearlayout android:id=" @+id/top "android:layout_width=" Wrap_content "Android oid:layout_height= "Wrap_content" > <button android:id= "@+id/upload_image" android:layout_width= "wrap    _content "android:layout_height=" wrap_content "android:text=" Upload picture "/> </LinearLayout> <imageview android:id= "@+id/imageview" android:layout_below= "@id/top" Android:layout_centerinpar Ent= "true" android:layout_width= "wrap_content"android:layout_height=" Wrap_content "/> </RelativeLayout> 
      very simple, it is a button and a imageview to display the picture;

Next is mainactivity, see the OnCreate method directly:

@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Initview (); httputils = new Httputils (100000); Httputils.configcurrenthttpcacheexpiry (5000) ;}
 This method first calls Initview to initialize the interface, then creates a Httputils object, and sets his connection timeout to 100s, setting his cache validity time to 5s, to look at the Initview method:

/** * Initialize view control */public void Initview () {uploadimagebt = (Button) Findviewbyid (r.id.upload_image); ImageView = (ImageView ) Findviewbyid (R.id.imageview); Uploadimagebt.setonclicklistener (this);p Rogressdialog = Getprogressdialog ();// Get progress bar Dialoglistener = new Dialoginterface.onclicklistener () {@Overridepublic void OnClick (dialoginterface dialog, int which) {switch (which) {case 0:tempfile = new File (Environment.getexternalstoragedirectory (), Getphotofilename ());// Call System Photo Startcamera (dialog); break;case 1://Open System Gallery Startwall (dialog); break;default:break;}}; Mhandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {if (Msg.arg1 > 0) progressdialog.setprogress (MSG.ARG1);//Update Progress Bar}};}

First, the 9th line gets a ProgressDialog object, and the 10th Behavior selection dialog binds to the listener event, which is used to prompt the user to take a photo or get it from the gallery, which is defined as follows:

/** * Displays dialog (from photo or local gallery) of the selected image source * @param title * @param items */public void ShowDialog (String title,string[] items) {Aler Tdialog.builder dialog = new Alertdialog.builder (this). Settitle (title). Setitems (items, dialoglistener);// Show Dialogdialog.show ();}
If you choose to take a photo, the system camera is invoked by the Startcamera method:

/** * Call camera to take photos * @param dialog */public void Startcamera (Dialoginterface dialog) {Dialog.dismiss ();//Hide the dialog//of the selected photo source first Call the system's camera function Intent intent = new Intent (mediastore.action_image_capture); Intent.putextra ("Camerasensortype", 2);// Call the front camera Intent.putextra ("autofocus", true);//Perform AF operation Intent.putextra ("fullscreen", false);//Set Full screen Intent.putextra (" Showactionicons ", false); Intent.putextra (Mediastore.extra_output, Uri.fromfile (tempfile));// Specifies the location Startactivityforresult (intent, Photo_camera) where the camera was photographed after it was called.
This method first hides the selection dialog box, then turns on the system camera and makes the appropriate settings, specifies where to save the photo, and finally wraps the photo results back in intent before returning to the previous activity, and sets the return flag to Photo_camera;

If you choose a photo album, you can get an SD image by calling the Startwall method:

/** * Open System Gallery * @param dialog */public void Startwall (Dialoginterface dialog) {Dialog.dismiss ();//Set hide dialogintent intent = New Intent (Intent.action_pick,android.provider.mediastore.images.media.external_content_uri); Intent.setdataandtype (MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); Startactivityforresult (Intent, Photo_wall);}
The method also first hides the selection dialog box, and then calls the system service to display all the existing images in the SD card, and returns the picture information via intent, while setting the return flag to Photo_wall;

Let's look at what the different return flags are doing.

@Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {Super.onactivityresult ( Requestcode, ResultCode, data), switch (requestcode) {case photo_camera://represents the photo obtained from the camera and needs to be cropped startphotocut ( Uri.fromfile (tempfile), 300,true); Break;case photo_wall:if (null! = data) Startphotocut (Data.getdata (), 300,false); Break;case photo_store:if (null! = data) {Setpicturetoimageview (data,true);} Break;case photo_not_store:if (null! = data) {Setpicturetoimageview (data,false);} Break;default:break;}}
This method is called by the system after the call Startactivityforresult, see we just saw the Photo_camrea and Photo_wall flag, the first choice to see Photo_camrea, He would call startphotocut to crop the photos and see the Startphotocut method:

/** * Crop a picture to a specified size * @param URI * @param size * @param flag */public void Startphotocut (URI uri,int Size,boolean flag) {Inten T intent = new Intent ("Com.android.camera.action.CROP"); Intent.setdataandtype (URI, "image/*"); Intent.putextra ("CROP ", true);//Set the view in intent to be clipped//set aspect ratio Intent.putextra (" Aspectx ", 1); Intent.putextra (" Aspecty ", 1);// Sets the width height of the cropped picture Intent.putextra ("Outputx", size), Intent.putextra ("Outputy", size);//sets whether to return data Intent.putextra (" Return-data ", true); if (flag = = True) Startactivityforresult (intent, photo_store); else{tempintent = intent;try { Startactivityforresult (Tempintent, Photo_not_store); System.out.println ("haha");} catch (Exception e) {System.out.println (e.tostring ());}}}
The first few lines of this method are some of the settings for cropping the photo, and then using the flag flag to determine whether to store the photo on the SD card, because if flag is false, it means that this picture is obtained from the library, and he comes from the SD card, so there is no need to save it again. Thus returns the flag Photo_not_store, if the flag is true, you need to store it again, return the flag Photo_store, the same call is the Startactivityforresult method, Then he will also execute the Onactivityresult method;

Then for the Photo_wall flag, if the selected picture is not empty, then the implementation of the Startphotocut method, the same crop;

For the Photo_not_store and Photo_store flags, they will execute the Setpicturetoimageview method, so we can look directly at his code:

/** * display pictures to ImageView Above * @param data * @param flag indicates true if the photo is taken, if it is a photo from the system, false */public void Setpicturetoimageview (Intent data, Boolean flag) {Bundle bundle = Data.getextras (); if (null! = Bundle) {Bitmap Bitmap = bundle.getparcelable ("Data"); Imageview.setimagebitmap (bitmap);//Display the picture to the imageView above//upload the image to the server if (flag = = False) {//need to first modify the value of the tempfile string path = Getselectphotopath (tempintent); System.out.println ("Path:" +path); tempfile = new File (path);//uploadpicture ();//upload image uploadthread thread = new Uploadthread (); Thread.Start ();} Else{//uploadpicture ();//upload image uploadthread thread = new Uploadthread (); Thread.Start ();} if (flag = = True) savepicturetosd (bitmap);//Save picture to sd card}} 
This method does a lot of things, first of all, he will get from intent to get to the picture and display to ImageView above, then call Uploadthread thread to upload the picture to the server, If the flag is true indicates that the picture needs to be stored locally, then we need to call Savepicturetosd to store the picture, first look at the Uploadthread thread:

Class Uploadthread extends thread{@Overridepublic void Run () {uploadpicture ();}}
very simply, there is only one uploadpicture method, and naturally we need to look at the Uploadpicture code:

/** * Upload image to database */public void Uploadpicture () {requestparams params = new Requestparams ();p arams.addbodyparameter ("MSG", Tempfile.getabsolutepath ());p Arams.addbodyparameter (Tempfile.getpath (). Replace ("/", ""), tempfile); Httputils.send (Httpmethod.post, Url,params,new requestcallback<string> () {@Overridepublic void OnStart () { Progressdialog.show ();//Show progress bar} @Overridepublic void OnFailure (HttpException arg0, String arg1) {System.out.println (" Upload failed "); System.out.println (Arg0.tostring ());//Hide Progress bar progressdialog.dismiss () after upload failure;} @Overridepublic void onloading (long total, long current, Boolean isuploading) {System.out.println ("Current/total:" + current+ "/" +total); int process = 0;IF (Total! = 0) {process = (int) (current/(total/100));} Message message = new Message (); message.arg1 = process;mhandler.sendmessage (message); super.onloading (total, Current, isuploading); } @Overridepublic void onsuccess (responseinfo<string> arg0) {System.out.println ("upload succeeded");// Hide Progress bar Progressdialog.dismiss ();}) after uploading successfully;}
This part is used to xutils of the httputils part of the first set up some request parameters, and then call Httputils Send method to request, in order to be able to upload the results more intuitive, we added a progress bar, The OnStart method is to upload the execution of the start call method, we show the progress bar here, onloading is the upload process execution method, about every second will be executed once, We are here through the handler message mechanism to encapsulate progress into a message object to send it to handler processing, the specific update progress bar code is in our Initview method above, because he can only be updated in the main thread, Finally, after the failure or success of the electrophoresis, call ProgressDialog's dismiss method to hide the progress bar;

Finally, just save the image to the SD card operation, this is relatively simple, just simple file storage operation, but the path is the SD card only:

/** * Save picture to SD card * @param bitmap */public void Savepicturetosd (bitmap bitmap) {Bytearrayoutputstream BAOs = new Bytearrayo Utputstream (); FileOutputStream fos = null;bitmap.compress (Bitmap.CompressFormat.JPEG, BAOs);//The 2nd parameter represents the compression ratio, 100 means do not compress try {fos = new FileOutputStream (tempfile); Fos.write (Baos.tobytearray ()); Fos.flush ();} catch (Exception e) {e.printstacktrace ();} finally{try {if (null! = BAOs) {    baos.close ();    BAOs = null;} if (null! = FOS) {fos.close (); fos = null;}} catch (Exception E2) {}}}
at this point, the client code is explained, followed by the server-side code:

server-side:

The code is relatively small, the direct copy comes out:

public class Uploadservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Response) throws Servletexception, IOException {doPost (request, response);} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Request.setcharacterencoding ("Utf-8"); Response.setcharacterencoding ("Utf-8"); Response.setcontenttype ("text/ Html,charset=utf-8 "); Smartupload smartupload = new Smartupload ();        String msg= null;             try {smartupload.initialize (This.getservletconfig (), request, response);              Smartupload.upload ();            msg = Smartupload.getrequest (). GetParameter ("msg");            System.out.println (Smartupload.getfiles (). GetCount ());              Com.jspsmart.upload.File smartfile = Smartupload.getfiles (). GetFile (0); if (!smartfile.ismissing ()) {String savefilename = Getservletcontext (). Getrealpath ("/") + "images\\" + SMA          Rtfile.getfilename ();        System.out.println (Savefilename);              Smartfile.saveas (Savefilename, smartupload.save_physical);        }} catch (Exception e) {e.printstacktrace (); } }}

The most important is the Dopost method, this example uses the Smartupload way to achieve file upload operation, of course, you can also use other methods, as for the jar package and other sources will download links to the project inside, The 18th line first initializes the Smartupload, then calls the upload method to prepare the upload, the 22nd line obtains the client to upload the file the first file, from here we can also see that smartupload is supporting multi-file upload, and then 23rd line to determine whether the file exists, 24 lines to generate the path of the file, 26 rows of file storage operations, note that smartupload.save_physical means absolute path, so your file storage path must be the full path, so that the server-side code to explain the end is not very simple ah, To remind you of the configuration of Web. XML, my configuration is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-app_2_5.xsd "id=" webapp_id "version=" 2.5 "><servlet><servlet-name> Uploadservlet</servlet-name>        <servlet-class>com.hzw.servlet.uploadservlet</servlet-class ></servlet><servlet-mapping>    <servlet-name>UploadServlet</servlet-name>        <url-pattern>/upload</url-pattern>    </servlet-mapping></web-app>
basically the end of the explanation, remember in the client do not forget to add Network access and SD card access rights ha:

    <uses-permission android:name= "Android.permission.READ_EXTERNAL_STORAGE"/>     <uses-permission Android : Name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>    <uses-permission android:name= " Android.permission.INTERNET "></uses-permission>    <uses-permission android:name=" Android.permission.ACCESS_NETWORK_STATE "></uses-permission>
Click here to download the source!!!!!
















Android-----based on xutils photo upload client and server-side implementation

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.