Android 带有progressbar的MultipartEntityBuilder

Android 带有progressbar的MultipartEntityBuilder,android,multipartentity,Android,Multipartentity,我使用以下代码使用MultipartEntityBuilder将照片上载到我的服务器。最后的某个地方写着//FIXME把你的进度条放在这里。我不知道是否应该将整个函数放入Asynctask,或者在上传文件时应该如何显示进度 我查过了,但没什么用 public String postFile(String fileName) throws Exception { fileName = "/mnt/sdcard/DCIM/100MEDIA/IMAG0309.jpg";

我使用以下代码使用MultipartEntityBuilder将照片上载到我的服务器。最后的某个地方写着
//FIXME把你的进度条放在这里。我不知道是否应该将整个函数放入Asynctask,或者在上传文件时应该如何显示进度

我查过了,但没什么用

public String postFile(String fileName) throws Exception {

          fileName = "/mnt/sdcard/DCIM/100MEDIA/IMAG0309.jpg";

            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost("http://www.mywebsite.com/upload_file.php");
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();        
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);  

            final File file = new File(fileName);
            FileBody fb = new FileBody(file);
            builder.addPart("file",fb);

            String userid = session_userid;
            builder.addTextBody("userID", userid);

            final HttpEntity yourEntity = builder.build();

            class ProgressiveEntity implements HttpEntity {
                @Override
                public void consumeContent() throws IOException {
                    yourEntity.consumeContent();                
                }
                @Override
                public InputStream getContent() throws IOException,
                        IllegalStateException {
                    return yourEntity.getContent();
                }
                @Override
                public Header getContentEncoding() {             
                    return yourEntity.getContentEncoding();
                }
                @Override
                public long getContentLength() {
                    return yourEntity.getContentLength();
                }
                @Override
                public Header getContentType() {
                    return yourEntity.getContentType();
                }
                @Override
                public boolean isChunked() {             
                    return yourEntity.isChunked();
                }
                @Override
                public boolean isRepeatable() {
                    return yourEntity.isRepeatable();
                }
                @Override
                public boolean isStreaming() {             
                    return yourEntity.isStreaming();
                } // CONSIDER put a _real_ delegator into here!

                @Override
                public void writeTo(OutputStream outstream) throws IOException {

                    class ProxyOutputStream extends FilterOutputStream {

                        public ProxyOutputStream(OutputStream proxy) {
                            super(proxy);    
                        }
                        public void write(int idx) throws IOException {
                            out.write(idx);
                        }
                        public void write(byte[] bts) throws IOException {
                            out.write(bts);
                        }
                        public void write(byte[] bts, int st, int end) throws IOException {
                            out.write(bts, st, end);
                        }
                        public void flush() throws IOException {
                            out.flush();
                        }
                        public void close() throws IOException {
                            out.close();
                        }
                    }

                    class ProgressiveOutputStream extends ProxyOutputStream {

                         int totalSent;

                        public ProgressiveOutputStream(OutputStream proxy) {
                            super(proxy);
                        }
                        public void write(byte[] bts, int st, int end) throws IOException {

                            // FIXME  Put your progress bar stuff here!

                            out.write(bts, st, end);
                        }
                    }

                    yourEntity.writeTo(new ProgressiveOutputStream(outstream));
                }

            };
            ProgressiveEntity myEntity = new ProgressiveEntity();

            post.setEntity(myEntity);
            HttpResponse response = client.execute(post);        

                return getContent(response);

   } 
这就是我所做的,但我仍然需要你们来完成它:

 @Override
            protected String doInBackground(HttpResponse... arg0)
            {
              String fileName = "/mnt/sdcard/DCIM/100MEDIA/IMAG0309.jpg";
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost("http://www.mywebsite.com/upload_file.php");
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();        
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);  

                final File file = new File(fileName);
                FileBody fb = new FileBody(file);
                builder.addPart("file",fb);

                    String userid = session_userid;
                builder.addTextBody("userID", userid);
                final HttpEntity yourEntity = builder.build();

                class ProgressiveEntity implements HttpEntity {
                    @Override
                    public void consumeContent() throws IOException {
                        yourEntity.consumeContent();                
                    }
                    @Override
                    public InputStream getContent() throws IOException,
                            IllegalStateException {
                        return yourEntity.getContent();
                    }
                    @Override
                    public Header getContentEncoding() {             
                        return yourEntity.getContentEncoding();
                    }
                    @Override
                    public long getContentLength() {
                        return yourEntity.getContentLength();
                    }
                    @Override
                    public Header getContentType() {
                        return yourEntity.getContentType();
                    }
                    @Override
                    public boolean isChunked() {             
                        return yourEntity.isChunked();
                    }
                    @Override
                    public boolean isRepeatable() {
                        return yourEntity.isRepeatable();
                    }
                    @Override
                    public boolean isStreaming() {             
                        return yourEntity.isStreaming();
                    } // CONSIDER put a _real_ delegator into here!

                    @Override
                    public void writeTo(OutputStream outstream) throws IOException {

                        class ProxyOutputStream extends FilterOutputStream {

                            public ProxyOutputStream(OutputStream proxy) {
                                super(proxy);    
                            }
                            public void write(int idx) throws IOException {
                                out.write(idx);
                            }
                            public void write(byte[] bts) throws IOException {
                                out.write(bts);
                            }
                            public void write(byte[] bts, int st, int end) throws IOException {
                                out.write(bts, st, end);
                            }
                            public void flush() throws IOException {
                                out.flush();
                            }
                            public void close() throws IOException {
                                out.close();
                            }
                        }

                        class ProgressiveOutputStream extends ProxyOutputStream {
                            public ProgressiveOutputStream(OutputStream proxy) {
                                super(proxy);
                                int totalSent = 0;
                            }
                            public void write(byte[] bts, int st, int end) throws IOException {

                                // FIXME  Put your progress bar stuff here!
                                 //what's totalSize?
                                publishProgress((int) ((end / (float) totalSize) * 100));
                                out.write(bts, st, end);
                            }
                        }

                        yourEntity.writeTo(new ProgressiveOutputStream(outstream));
                    }

                };
                ProgressiveEntity myEntity = new ProgressiveEntity();

                post.setEntity(myEntity);
                HttpResponse response = client.execute(post);        

                    return getContent(response);
//Here it says I should put this into a try catch but then I get an error on
// the doInBackground line saying it needs to return a string

                }

                protected void onProgressUpdate(Integer... progress) {
                    pd.setProgress((int) (progress[0]));
               }

            @SuppressWarnings("deprecation")
            @Override
             protected void onPostExecute(String file_url) {
                pd.dismiss();
                connection.disconnect();
                Toast.makeText(getApplicationContext(), "Ready.", Toast.LENGTH_LONG).show();
            }

        }

我试图实现类似的目标(我使用
ProgressDialog
而不是
ProgressBar
)。您必须使用
AsyncTask
,这样主线程就不会等待上载完成(上载必须是异步的)

  • HttpEntityWrapped
    (信用证:)创建扩展名:

    }

  • 我已经创建了一个私有类,它在
    活动中扩展
    异步任务
    。在
    doInBackground
    中,您可以使用
    MultipartEntityBuilder
    添加文件和所需的任何内容。如果上传成功(code==200,这是我的自定义json响应),将调用
    onPostExecute

    私有类UploadAsyncTask扩展了AsyncTask{

    private Context context;
    private Exception exception;
    private ProgressDialog progressDialog;
    
    private UploadAsyncTask(Context context) {
    
        this.context = context;
    }
    
    @Override
    protected Boolean doInBackground(String... params) {
    
        String uploadUrl = URL + "upload";
    
        HttpResponse response = null;
    
        try {
            HttpPost post = new HttpPost(uploadUrl);
    
            // Entity
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            // Add your file
            multipartEntityBuilder.addPart("file", new FileBody(new File(params[0])));
    
            // Progress listener - updates task's progress
            MyHttpEntity.ProgressListener progressListener =
                    new MyHttpEntity.ProgressListener() {
                        @Override
                        public void transferred(float progress) {
                            UploadAsyncTask.this.publishProgress((int) progress);
                        }
                    };
    
            // POST
            post.setEntity(new MyHttpEntity(multipartEntityBuilder.build(),
                    progressListener));
    
            // Handle response
            GsonBuilder builder = new GsonBuilder();
            LinkedTreeMap object = builder.create().fromJson(
                    EntityUtils.toString(client.execute(post).getEntity()),
                    LinkedTreeMap.class);
    
            if ((double) object.get("code") == 200.0) {
                return true;
            }
    
        } catch (UnsupportedEncodingException | JsonSyntaxException | ClientProtocolException e) {
            e.printStackTrace();
            Log.e("UPLOAD", e.getMessage());
            this.exception = e;
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        return false;
    }
    
    @Override
    protected void onPreExecute() {
    
        // Init and show dialog
        this.progressDialog = new ProgressDialog(this.context);
        this.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        this.progressDialog.show();
    }
    
    @Override
    protected void onPostExecute(Boolean result) {
    
        // Close dialog
        this.progressDialog.dismiss();
        if (result) {
            Toast.makeText(getApplicationContext(),
                    R.string.upload_success, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(),
                    R.string.upload_failure, Toast.LENGTH_LONG).show();
        }
    }
    
    @Override
    protected void onProgressUpdate(Integer... progress) {
        // Update process
        this.progressDialog.setProgress((int) progress[0]);
    }
    
    }

  • Acitvity
    中调用上载:

    私有void_upload(){

    }


  • 我试图实现类似的目标(我使用
    ProgressDialog
    而不是
    ProgressBar
    )。您必须使用
    AsyncTask
    ,这样主线程就不会等待上载完成(上载必须是异步的)

  • HttpEntityWrapped
    (信用证:)创建扩展名:

    }

  • 我已经创建了一个私有类,它在
    活动中扩展
    异步任务
    。在
    doInBackground
    中,您可以使用
    MultipartEntityBuilder
    添加文件和所需的任何内容。如果上传成功(code==200,这是我的自定义json响应),将调用
    onPostExecute

    私有类UploadAsyncTask扩展了AsyncTask{

    private Context context;
    private Exception exception;
    private ProgressDialog progressDialog;
    
    private UploadAsyncTask(Context context) {
    
        this.context = context;
    }
    
    @Override
    protected Boolean doInBackground(String... params) {
    
        String uploadUrl = URL + "upload";
    
        HttpResponse response = null;
    
        try {
            HttpPost post = new HttpPost(uploadUrl);
    
            // Entity
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            // Add your file
            multipartEntityBuilder.addPart("file", new FileBody(new File(params[0])));
    
            // Progress listener - updates task's progress
            MyHttpEntity.ProgressListener progressListener =
                    new MyHttpEntity.ProgressListener() {
                        @Override
                        public void transferred(float progress) {
                            UploadAsyncTask.this.publishProgress((int) progress);
                        }
                    };
    
            // POST
            post.setEntity(new MyHttpEntity(multipartEntityBuilder.build(),
                    progressListener));
    
            // Handle response
            GsonBuilder builder = new GsonBuilder();
            LinkedTreeMap object = builder.create().fromJson(
                    EntityUtils.toString(client.execute(post).getEntity()),
                    LinkedTreeMap.class);
    
            if ((double) object.get("code") == 200.0) {
                return true;
            }
    
        } catch (UnsupportedEncodingException | JsonSyntaxException | ClientProtocolException e) {
            e.printStackTrace();
            Log.e("UPLOAD", e.getMessage());
            this.exception = e;
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        return false;
    }
    
    @Override
    protected void onPreExecute() {
    
        // Init and show dialog
        this.progressDialog = new ProgressDialog(this.context);
        this.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        this.progressDialog.show();
    }
    
    @Override
    protected void onPostExecute(Boolean result) {
    
        // Close dialog
        this.progressDialog.dismiss();
        if (result) {
            Toast.makeText(getApplicationContext(),
                    R.string.upload_success, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(),
                    R.string.upload_failure, Toast.LENGTH_LONG).show();
        }
    }
    
    @Override
    protected void onProgressUpdate(Integer... progress) {
        // Update process
        this.progressDialog.setProgress((int) progress[0]);
    }
    
    }

  • Acitvity
    中调用上载:

    私有void_upload(){

    }


  • 您可以将其包装在AsyncTask中,使用onPrexcute()显示进度条,并将进度条隐藏在onPostExecute()中……假设您关心的只是一个不确定的进度条。不是真的……我想显示进度。顺便问一下,你有一个不确定进度条的示例代码吗?早些时候,我使用了更简单的DataOutputStream,在显示进度时使用Asynctask上传文件,所以我可能会弄明白。只需将a与android:UndeterminatedRavable=“@drawable/yourDrawable”AttAttribute一起使用即可。@erdomester您找到解决方案了吗?我不理解这个问题,因为您无法从android的UI线程中使用HTTP(或任何*TP),因此,您需要一个后台线程,因此您需要AsyncTask所做的一切,所以只需使用它。换句话说,“ProgressBar?”和“AsyncTask?”的问题与上载文件的问题是不相关的,因此,如果您使用它们的示例开始使用它们,然后才放入HTTP内容(然后才放入ProgressiveEntity),您可能会遇到一些问题。您可以将其包装在AsyncTask中,使用onPrexcute()显示进度条,并将进度条隐藏在onPostExecute()中…假设您只关心不确定的进度条。不是真的…我想显示进度。顺便问一下,你有一个不确定进度条的示例代码吗?早些时候,我使用了更简单的DataOutputStream,在显示进度时使用Asynctask上传文件,所以我可能会弄明白。只需将a与android:UndeterminatedRavable=“@drawable/yourDrawable”AttAttribute一起使用即可。@erdomester您找到解决方案了吗?我不理解这个问题,因为您无法从android的UI线程中使用HTTP(或任何*TP),因此,您需要一个后台线程,因此您需要AsyncTask所做的一切,所以只需使用它。换句话说,“ProgressBar?”和“AsyncTask?”的问题与上载文件的问题是不相关的,因此,如果您使用它们的示例开始使用它们,然后才放入HTTP内容(然后才放入ProgressiveEntity),那么您可能会遇到一些问题。
    UploadAsyncTask task = new UploadAsyncTask(this);
    task.execute();