我需要知道已经上传了多少字节来更新进度条android

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我需要知道已经上传了多少字节来更新进度条android相关的知识,希望对你有一定的参考价值。

我正在开发一个用于上传视频到Apache / php服务器的应用程序。在这一刻,我已经可以上传视频了。我需要在上传文件时显示进度条。我有下一个代码使用AsyncTask和HTTP 4.1.1库来模拟FORM。

class uploadVideo extends AsyncTask<Void,Void,String>{

    @Override
    protected String doInBackground(Void... params) {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.youtouch.cl/videoloader/index.php");           
        try {
            // Add your data
            File input=new File(fileName);              

            MultipartEntity multi=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);                

            multi.addPart("video", new FileBody(input));                

            httppost.setEntity(multi);

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);               

            HttpEntity entity = response.getEntity();

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(
                            entity.getContent(), "UTF-8"));
            String sResponse = reader.readLine();
            return sResponse;

        } catch (ClientProtocolException e) {
            Log.v("Uri Galeria", e.toString());
            e.printStackTrace();                

        } catch (IOException e) {
            Log.v("Uri Galeria", e.toString());
            e.printStackTrace();                
        }
        return "error";
    }

    @Override
    protected void onProgressUpdate(Void... unsued) {
                //Here I do should update the progress bar
    }

    @Override
    protected void onPostExecute(String sResponse) {
        try {
            if (pd.isShowing())
                pd.dismiss();

            if (sResponse != null) {
                JSONObject JResponse = new JSONObject(sResponse);
                int success = JResponse.getInt("SUCCESS");
                String message = JResponse.getString("MESSAGE");
                if (success == 0) {
                    Toast.makeText(getApplicationContext(), message,
                            Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Video uploaded successfully",
                            Toast.LENGTH_SHORT).show();

                }
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(),
                    e.getMessage(),
                    Toast.LENGTH_LONG).show();
            Log.e(e.getClass().getName(), e.getMessage(), e);
        }
    }

我需要知道在哪里可以获得已上传的字节数。 File.length是总大小。

答案

在这里查看我的答案,我想它会回答你的问题:但是将图像的文件路径更新为你要上传的视频

https://stackoverflow.com/questions/15572747/progressbar-in-asynctask-is-not-showing-on-upload

另一答案

你试过扩展FileBody吗?据推测,POST将调用getInputStream()writeTo()以实际将文件数据发送到服务器。您可以扩展其中任何一个(包括getInputStream()返回的InputStream)并跟踪已发送的数据量。

另一答案

感谢cyngus的想法,我已经解决了这个问题。我添加了下一个跟踪上传字节的代码:

上传按钮上的监听器:

    btnSubir.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            //pd = ProgressDialog.show(VideoandroidActivity.this, "", "Subiendo Video", true, false);

            pd = new ProgressDialog(VideoAndroidActivity.this);
            pd.setMessage("Uploading Video");
            pd.setIndeterminate(false);
            pd.setMax(100);
            pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pd.show();
            //Thread thread=new Thread(new threadUploadVideo());
            //thread.start();
            new UploadVideo().execute();
        }
    });

Asynctask用于运行上传:

class UploadVideo extends AsyncTask<Void,Integer,String> {
    private FileBody fb;

    @Override
    protected String doInBackground(Void... params) {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.youtouch.cl/videoloader/index.php");   
        int count;
        try {
            // Add your data
            File input=new File(fileName);

            // I created a Filebody Object
            fb=new FileBody(input);
            MultipartEntity multi=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            multi.addPart("video",fb);          

            httppost.setEntity(multi);              
            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            //get the InputStream
            InputStream is=fb.getInputStream();

            //create a buffer
            byte data[] = new byte[1024];//1024

            //this var updates the progress bar
            long total=0;
            while((count=is.read(data))!=-1){
                total+=count;
                publishProgress((int)(total*100/input.length()));
            }
            is.close();             
            HttpEntity entity = response.getEntity();

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(
                            entity.getContent(), "UTF-8"));
            String sResponse = reader.readLine();
            return sResponse;

        } catch (ClientProtocolException e) {
            Log.v("Uri Galeria", e.toString());
            e.printStackTrace();                

        } catch (IOException e) {
            Log.v("Uri Galeria", e.toString());
            e.printStackTrace();                
        }
        return "error";
    }

    @Override
    protected void onProgressUpdate(Integer... unsued) {        
        pd.setProgress(unsued[0]);
    }

    @Override
    protected void onPostExecute(String sResponse) {
        try {
            if (pd.isShowing())
                pd.dismiss();

            if (sResponse != null) {
                    Toast.makeText(getApplicationContext(),sResponse,Toast.LENGTH_SHORT).show();
                    Log.i("Splash", sResponse);                 
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(),
                    e.getMessage(),
                    Toast.LENGTH_LONG).show();
            Log.e(e.getClass().getName(), e.getMessage(), e);
        }
    }


}

进度条加载有点慢(在启动时似乎是冻结,然后加载1到100非常快),但工作。

对不起,我的英语很正常:(。

另一答案

我以前做的是扩展org.apache.http.entity.ByteArrayEntity并覆盖writeTo函数,如下所示,而字节输出它将通过writeTo(),所以你可以计算当前输出字节:

@Override
public void writeTo(final OutputStream outstream) throws IOException 
{
    if (outstream == null) {
        throw new IllegalArgumentException("Output stream may not be null");
    }

    InputStream instream = new ByteArrayInputStream(this.content);

    try {
        byte[] tmp = new byte[512];
        int total = (int) this.content.length;
        int progress = 0;
        int increment = 0;
        int l;
        int percent;

        // read file and write to http output stream
        while ((l = instream.read(tmp)) != -1) {
            // check progress
            progress = progress + l;
            percent = Math.round(((float) progress / (float) total) * 100);

            // if percent exceeds increment update status notification
            // and adjust increment
            if (percent > increment) {
                increment += 10;
                // update percentage here !!
            }

            // write to output stream
            outstream.write(tmp, 0, l);
        }

        // flush output stream
        outstream.flush();
    } finally {
        // close input stream
        instream.close();
    }
}

以上是关于我需要知道已经上传了多少字节来更新进度条android的主要内容,如果未能解决你的问题,请参考以下文章

Azure Blob 存储多个同时上传的进度

使用 jQuery 的文件上传进度条

使用 jQuery 的文件上传进度条

oss上传文件进度条展示

将图像上传到 Firebase 存储时如何制作进度条?

使用请求通过 http 下载文件时的进度条