Uploading images to the server via Android client

Source: Internet
Author: User
Tags http post

Yesterday, (in my previous blog) wrote a browser to upload images to the server (PHP), today to put this feature into practice. (also improved the code of the service side)

Do not try not to know, the original through the Android to the server to send pictures is really a very troublesome thing.

Upload code:

/*ways to upload files to the server*/    Private voidUploadFile () {String end= "\ r \ n"; String Twohyphens= "--"; String Boundary= "*****"; Try{URL URL=NewURL (PostURL); HttpURLConnection Con=(HttpURLConnection) url.openconnection (); /*Output to the connection. Default is false, set to True because post method must write something to the connection*/Con.setdooutput (true); /*Read from the connection. Default is true.*/Con.setdoinput (true); /*Post cannot use caches*/Con.setusecaches (false); /*Set The Post method. Default is GET*/Con.setrequestmethod ("POST"); /*Set request Properties*/Con.setrequestproperty ("Connection", "keep-alive"); Con.setrequestproperty ("Charset", "UTF-8"); Con.setrequestproperty ("Content-type", "multipart/form-data;boundary=" +boundary); /*set Strictmode Otherwise the HttpURLConnection connection fails because this is a network connection in the main process*/Strictmode.setthreadpolicy (NewStrictMode.ThreadPolicy.Builder (). Detectdiskreads (). Detectdiskwrites (). Detectnetwork (). Penaltylog (). Build (          )); /*set the default call to connect () in Dataoutputstream,getoutputstream*/DataOutputStream DS=NewDataOutputStream (Con.getoutputstream ());//output to the connectionDs.writebytes (Twohyphens + boundary +end); Ds.writebytes ("Content-disposition:form-data;" + "name=\" file\ "filename=\" "+FileName+ "\"" +end);          Ds.writebytes (end); /*get the FileInputStream of the document*/FileInputStream fstream=NewFileInputStream (UploadFile); /*set 8192bytes per write*/            intBufferSize = 8192; byte[] buffer =New byte[BufferSize];//8k            intLength =-1; /*reading data from a file to a buffer*/             while(length = fstream.read (buffer))! =-1)            {            /*Write data to DataOutputStream*/ds.write (buffer,0, length);            } ds.writebytes (end); Ds.writebytes (Twohyphens+ Boundary + Twohyphens +end); /*turn off the stream, write something that automatically generates an HTTP body*/Fstream.close (); /*Close DataOutputStream*/Ds.close (); /*reads the response information from the returned input stream*/InputStream is= Con.getinputstream ();//input from the connection formally establishes an HTTP connection            intch; StringBuffer b=NewStringBuffer ();  while(ch = is.read ())! =-1) {b.append (Char) ch); }          /*Display Web page response content*///Toast.maketext (Mainactivity.this, b.tostring (). Trim (), Toast.length_short). Show ();//Post SuccessfulSystem.out.println (b.tostring ()); } Catch(Exception e) {/*Show exception Information*///Toast.maketext (Mainactivity.this, "Fail:" + E, Toast.length_short). Show ();//Post failedSystem.out.println (e); }    }

Boven said that uploading images must use the Post method, which is of course used in the Post method. There is no change in the upload and normal upload.

But I'm still not used to this method (I have been using the volley framework, I am interested in Baidu a bit.) A very useful framework that is officially launched, but I'm not going to study it if I need to use a map.

Basic steps for using the native post method:

1. Establish a connection using httpurlconnection

2. Set request Properties

3. Assemble parameters according to the request format (cumbersome, can send a POST request via the browser, remove debug information comparison)

4. Create the input stream and write the data (where FileInputStream and below loops write)

5. Get the return stream and process the return parameter

6. Turn off all streams

This part of the code is almost entirely reference to the great God's writing. There are a lot of comments inside and I don't say much.

It is worth mentioning that after the 4.0 (Android version) has not been supported in the main thread to perform uploads, downloads and other time-consuming operations.

This is also reasonable, if you upload the file, suddenly your network is not good, you will always upload status. The experience is not good.

So calling the method above requires creating a new thread:

New Thread (new  Runnable () {                    @Override                    publicvoid  run () {                        UploadFile ();                    }                }). Start ();

This method is called when uploading the method with the same file as the method can be written, if the upload method in a separate class file needs to be instantiated and then through

Instantiates the object name. UploadFile ();

Method call.

Server-side

In the Last post, it was just a simple implementation, receiving and transferring the image. This service side is perfect:

<?PHP/** * * * * * * * * * * * * * * * * * * * * * ------------* 401 Error method * Internal Error *------------*///ini_set ("Display_errors", "on");//error_reporting (E_all | E_STRICT);Header(' access-control-allow-origin: * ');//resolve a previous JavaScript cross-domain request$fileInfo=$_files[' File '];$maxSize= 2097152;//Maximum allowable value$allowExt=Array(' jpeg ', ' jpg ', ' png ', ' gif ', ' wbmp ');$flag=true;//detect if a real picture typeif($fileInfo[' Error ']==0){    //determine the size of the uploaded file        if($fileInfo[' Size ']>$maxSize){        $data= ' Upload file too large '; returnResponse::show (201, ' Error1 ',$data); Exit(); }    //$ext =strtolower (End (Explode ('. '), $fileInfo [' name '])); Get suffix        $ext=PathInfo($fileInfo[' Name '],pathinfo_extension); if(!In_array($ext,$allowExt)){                $data= ' Illegal file type '; returnResponse::show (202, ' Error2 ',$data); Exit(); }    //determine if the file was transmitted via HTTP POST        if(!Is_uploaded_file($fileInfo[' Tmp_name '])){                $data= ' file is not transmitted via HTTP POST '; returnResponse::show (203, ' Error3 ',$data); Exit(); }    //detect if the picture type is true        if($flag){        if(!getimagesize($fileInfo[' Tmp_name '])){                    $data= ' Not a true picture type '; returnResponse::show (204, ' Error4 ',$data); Exit(); }    }        //Create a folder corresponding to the ID        $id=$_get[' ID ']; if(!file_exists($id)){        mkdir(‘.. /files/'.$id); //chmod ($id, 0777);    }        if(@Move_uploaded_file($fileInfo[' Tmp_name '], '. /files/'.$id.‘ /‘.$fileInfo[' Name '])){        $data= ' File Upload succeeded '; returnResponse::show (k, ' OK ',$data); }Else{        $data= ' File upload failed '; returnResponse::show (404, ' Error5 ',$data); }}Else{    Switch($fileinfo[' Error ']){         Case1:$data= ' The upload file exceeds the value of the upload_max_filesize option in the PHP configuration file '; returnResponse::show (401, ' Error5 ',$data);  Break;  Case2:$data= ' exceeds the size of the form max_file_size limit '; returnResponse::show (402, ' Error5 ',$data);  Break;  Case3:$data= ' File part is uploaded '; returnResponse::show (403, ' Error5 ',$data);  Break;  Case4:$data= ' no option to upload file '; returnResponse::show (405, ' Error5 ',$data);  Break;  Case6:$data= ' No temp directory found '; returnResponse::show (405, ' Error5 ',$data);  Break;  Case7: Case8:$data= ' System error '; returnResponse::show (405, ' Error5 ',$data);  Break; }}

A variety of images are tested here. More reliable than yesterday, right? Also unifies the returned JSON format to facilitate the client to parse. (There is, the above service-side code is also borrowed from the teaching of the great God of the wording, slightly modified)

Uploading images to the server via Android client

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.