android - 将多个文件上传到android中的服务器时的进度条

标签 android file-upload asynchronous progress-bar

我从android上传文件(视频和照片)到php服务器 我使用这段代码:

@SuppressWarnings("deprecation")
protected String doInBackground(String... args) {

    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();

    Utils.d(Config.REST_SERVER + url_connect);

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(Config.REST_SERVER+url_connect);

    try {




      @SuppressWarnings("deprecation")
      MultipartEntity entity = new MultipartEntity();

      entity.addPart("userId", new StringBody(this.userId));
      entity.addPart("orderId", new StringBody(this.orderId));


      Utils.d("size totale avant  : "+this.files.size());

      int i = 0;
      for(File f:this.files){
          entity.addPart("nameFile", new StringBody(f.getName()));
          i++;
          entity.addPart("files[]", (ContentBody) new FileBody(f));
      }


      httppost.setEntity(entity);
      HttpResponse response = httpclient.execute(httppost);



      HttpEntity httpEntity = response.getEntity();
      is = httpEntity.getContent();

      try {
          BufferedReader reader = new BufferedReader(new InputStreamReader(
                  is, "iso-8859-1"), 8);
          StringBuilder sb = new StringBuilder();
          String line = null;
          while ((line = reader.readLine()) != null) {
              sb.append(line + "\n");
          }
          is.close();
          json = sb.toString();
      } catch (Exception e) {
          Log.e("Buffer Error", "Error converting result " + e.toString());
      }

      // try parse the string to a JSON object
      try {
          Log.d("Create Response", json);
          jObj = new JSONObject(json);
          Log.d("Create Response", jObj.toString());
      } catch (JSONException e) {
          Log.e("JSON Parser", "Error parsing data " + e.toString());
      }


    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }


    return null;
}

我想制作与文件一样多的进度条,这些进度条将根据发送到服务器的字节百分比更改状态

有什么办法吗

提前谢谢你

最佳答案

像这样尝试。

供引用GitHub上传 时显示Horizo​​ntal ProgressBar 的开源项目。它将在 ProgressBar 中显示 % of byte 上传。

public class MyMultipartEntity extends MultipartEntity{

            private final ProgressListener listener;

            public MyMultipartEntity(final ProgressListener listener)
            {
                    super();
                    this.listener = listener;
            }

            public MyMultipartEntity(final HttpMultipartMode mode, final ProgressListener listener)
            {
                    super(mode);
                    this.listener = listener;
            }

            public MyMultipartEntity(HttpMultipartMode mode, final String boundary, final Charset charset, final ProgressListener listener)
            {
                    super(mode, boundary, charset);
                    this.listener = listener;
            }

            @Override
            public void writeTo(final OutputStream outstream) throws IOException
            {
                    super.writeTo(new CountingOutputStream(outstream, this.listener));
            }

            public static interface ProgressListener
            {
                    void transferred(long num);
            }

            public static class CountingOutputStream extends FilterOutputStream
            {

                    private final ProgressListener listener;
                    private long transferred;

                    public CountingOutputStream(final OutputStream out, final ProgressListener listener)
                    {
                            super(out);
                            this.listener = listener;
                            this.transferred = 0;
                    }

                    public void write(byte[] b, int off, int len) throws IOException
                    {
                            out.write(b, off, len);
                            this.transferred += len;
                            this.listener.transferred(this.transferred);
                    }

                    public void write(int b) throws IOException
                    {
                            out.write(b);
                            this.transferred++;
                            this.listener.transferred(this.transferred);
                    }
            }
    }

如何在AsyncTask中使用它来展示ProgressBar

public class HttpUpload extends AsyncTask<Void, Integer, Void> {

        private Context context;
        private String imgPath;

        private HttpClient client;

        private ProgressDialog pd;
        private long totalSize;

        private static final String url = "YOUR_URL";

        public HttpUpload(Context context, String imgPath) {
                super();
                this.context = context;
                this.imgPath = imgPath;
        }

        @Override
        protected void onPreExecute() {
                //Set timeout parameters
                int timeout = 10000;
                HttpParams httpParameters = new BasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
                HttpConnectionParams.setSoTimeout(httpParameters, timeout);

                //We'll use the DefaultHttpClient
                client = new DefaultHttpClient(httpParameters);

                pd = new ProgressDialog(context);
                pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                pd.setMessage("Uploading Picture/Video...");
                pd.setCancelable(false);
                pd.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
                try {
                        File file = new File(imgPath);

                        //Create the POST object
                        HttpPost post = new HttpPost(url);

                        //Create the multipart entity object and add a progress listener
                        //this is a our extended class so we can know the bytes that have been transfered
                        MultipartEntity entity = new MyMultipartEntity(new ProgressListener()
                        {
                                @Override
                                public void transferred(long num)
                                {
                                        //Call the onProgressUpdate method with the percent completed
                                        publishProgress((int) ((num / (float) totalSize) * 100));
                                        Log.d("DEBUG", num + " - " + totalSize);
                                }
                        });
                        //Add the file to the content's body
                        ContentBody cbFile = new FileBody( file, "image/jpeg" );
                        entity.addPart("source", cbFile);

                        //After adding everything we get the content's lenght
                        totalSize = entity.getContentLength();

                        //We add the entity to the post request
                        post.setEntity(entity);

                        //Execute post request
                    HttpResponse response = client.execute( post );
                        int statusCode = response.getStatusLine().getStatusCode();

                    if(statusCode == HttpStatus.SC_OK){
                            //If everything goes ok, we can get the response
                                String fullRes = EntityUtils.toString(response.getEntity());
                                Log.d("DEBUG", fullRes);

                        } else {
                                Log.d("DEBUG", "HTTP Fail, Response Code: " + statusCode);
                        }

                } catch (ClientProtocolException e) {
                        // Any error related to the Http Protocol (e.g. malformed url)
                        e.printStackTrace();
                } catch (IOException e) {
                        // Any IO error (e.g. File not found)
                        e.printStackTrace();
                }


                return null;
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
                //Set the pertange done in the progress dialog
                pd.setProgress((int) (progress[0]));
        }

        @Override
        protected void onPostExecute(Void result) {
                //Dismiss progress dialog
                pd.dismiss();
        }

}

希望对您有所帮助。

关于android - 将多个文件上传到android中的服务器时的进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19662846/

相关文章:

c# - 是否可以在没有任何人的情况下执行异步操作 "knowing"?

android - 如何每分钟更新一个 Android 应用小部件

java - TELEPHONY_SERVICE 常量在一个类中无法识别,但在另一个类中

java - 如何使 ExpandableListView 不可选?

Web View 中的 java.lang.IllegalArgumentException

.Net multipart/form-data 表单 enctype 和 UTF-8 "special"个字符 => � (MVC w/HttpPostedFileBase)

asp.net - 我应该担心受感染的 zip 文件吗?

azure - 将同一文件同时上传到 Azure Blob 存储

java - 对象化 GAE/J Google App Engine : Understanding asynchronous load

c# - Xamarin iOS 同步运行具有返回值的任务