Android uses HttpClient to upload files to the PHP server and monitor the progress bar

Source: Internet
Author: User
Tags php server
The PHP code on the upload server is as follows :? Php $ target_path.tmp; directory of the received File $ target_path. ($ _ FILES [file] [name]); $ target_pathiconv (UTF-8, gb2312, $ target_path); if (move_uploaded_file ($ _ FILES [f

The PHP code on the upload server is as follows :? Php $ target_path =. /tmp/; // directory of the received File $ target_path = $ target_path. ($ _ FILES ['file'] ['name']); $ target_path = iconv (UTF-8, gb2312, $ target_path); if (move_uploaded_file ($ _ FILES ['f

Upload

Server-side PHP

The Code is as follows:

 
Monitoring progress implementation

First, define the listener interface, as shown below:

// Progress listener interface public interface ProgressListener {public void transferred (long transferedBytes );}

The key part of the implementation of monitoring progress is to record the number of transmitted bytes, so we need to reloadFilterOutputStream, Override the key method to implement the progress listening function, as shown below. In this example, the first reload isHttpEntityWrapperAs the name suggests, it means to sendHttpEntityTo calculate the total number of bytes, the Code is as follows:

// Outputs: indicates the number of sent bytes when the output stream is OutputStream. public class ProgressOutHttpEntity extends listener {private final ProgressListener listener; public ProgressOutHttpEntity (final HttpEntity entity, final ProgressListener listener) {super (entity); this. listener = listener;} public static class CountingOutputStream extends FilterOutputStream {private final ProgressListener listener; pri Vate long transferred; CountingOutputStream (final OutputStream out, final ProgressListener listener) {super (out); this. listener = listener; this. transferred = 0 ;}@ Override public void write (final byte [] B, final int off, final int len) throws IOException {// NO, double-counting, as super. write (byte [], int, int) // delegates to write (int ). // super. write (B, off, len); out. write (B, off, len); th Is. transferred + = len; this. listener. transferred (this. transferred) ;}@ Override public void write (final int B) throws IOException {out. write (B); this. transferred ++; this. listener. transferred (this. transferred) ;}@ Override public void writeTo (final OutputStream out) throws IOException {this. wrappedEntity. writeTo (out instanceof CountingOutputStream? Out: new CountingOutputStream (out, this. listener ));}}

Finally, it is very simple to use the class and Httpclient implemented above to upload and display the progress. The Code is as follows: Use AsyncTask for asynchronous upload.

Public class FileUploadAsyncTask extends AsyncTask
 
  
{Private String url =" http://192.168.83.213/receive_file.php "; Private Context context; private ProgressDialog pd; private long totalSize; public FileUploadAsyncTask (Context context) {this. context = context ;}@ Override protected void onPreExecute () {pd = new ProgressDialog (context); pd. setProgressStyle (ProgressDialog. STYLE_HORIZONTAL); pd. setMessage ("Uploading .... "); pd. setCancelable (false); pd. show () ;}@ Override protected String doInBackground (File... params) {// Save the information of the file to be uploaded. MultipartEntityBuilder entitys = MultipartEntityBuilder. create (); entitys. setMode (HttpMultipartMode. BROWSER_COMPATIBLE); entitys. setCharset (Charset. forName (HTTP. UTF_8); File file = params [0]; entitys. addPart ("file", new FileBody (file); HttpEntity httpEntity = entitys. build (); totalSize = httpEntity. getContentLength (); ProgressOutHttpEntity progressHttpEntity = new ProgressOutHtt PEntity (httpEntity, new ProgressListener () {@ Override public void transferred (long transferedBytes) {publishProgress (int) (100 * transferedBytes/totalSize ));}}); return uploadFile (url, progressHttpEntity) ;}@ Override protected void onProgressUpdate (Integer... progress) {pd. setProgress (int) (progress [0]) ;}@ Override protected void onPostExecute (String result) {pd. dismiss (); Toast. make Text (context, result, Toast. LENGTH_SHORT ). show () ;}// upload the file to the server // server address // file public static String uploadFile (String url, ProgressOutHttpEntity entity) {HttpClient httpClient = new DefaultHttpClient (); httpClient. getParams (). setParameter (CoreProtocolPNames. PROTOCOL_VERSION, HttpVersion. HTTP_1_1); // sets the connection timeout value. getParams (). setParameter (CoreConnectionPNames. CONNECTION_TIMEOUT, 5000); HttpP Ost httpPost = new HttpPost (url); httpPost. setEntity (entity); try {HttpResponse httpResponse = httpClient.exe cute (httpPost); if (httpResponse. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK) {return "File Uploaded successfully";} catch (ClientProtocolException e) {e. printStackTrace ();} catch (ConnectTimeoutException e) {e. printStackTrace ();} catch (Exception e) {e. printStackTrace ();} finally {if (http Client! = Null & httpClient. getConnectionManager ()! = Null) {httpClient. getConnectionManager (). shutdown () ;}} return "File Upload Failed ";}}
 

Source code: Download

Andu blog? Android uses HttpClient to upload files to the PHP server and monitor the progress bar

Backup: http://download.csdn.net/detail/jdsjlzx/8486479

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.