1

我将文件(视频和照片)从 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;
}

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

有没有办法做到这一点

先感谢您

4

1 回答 1

2

像这样试试。

供参考GitHub开源项目Horizontal ProgressBar上传时显示。它将显示% 的字节上传ProgressBar

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();
        }

}

希望这会帮助你。

于 2013-10-29T16:02:55.023 回答