Android:更新文件上传的进度条

时间:2012-08-09 15:49:57

标签: android progress-bar progressdialog

我已经坚持了一段时间。我有一个异步任务,将图像上传到Web服务器。工作正常。

我为此设置了一个进度条对话框。我的问题是如何准确更新进度条。我尝试的所有东西都会导致它从一步到0-100。如果需要5秒或2分钟则无关紧要。上传完成后,栏会挂到0,然后点击100。

这是我的doInBackground代码。任何帮助表示赞赏。

编辑:我更新了以下代码以包含整个AsynchTask

private class UploadImageTask extends AsyncTask<String,Integer,String> {

        private Context context;   
        private String msg = "";
        private boolean running = true;

        public UploadImageTask(Activity activity) {
            this.context = activity;
            dialog = new ProgressDialog(context);
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.setMessage("Uploading photo, please wait.");
            dialog.setMax(100);
            dialog.setCancelable(true);
        }


    @Override
    protected void onPreExecute() {
            dialog.show();
            dialog.setOnDismissListener(mOnDismissListener);
    }



    @Override
    protected void onPostExecute(String msg){

         try {
        // prevents crash in rare case where activity finishes before dialog
        if (dialog.isShowing()) {
                dialog.dismiss();
        }
              } catch (Exception e) {
              } 
     }


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








    @Override
    protected String doInBackground(String... urls) {

                if(running) {

                    // new file upload
                    HttpURLConnection conn = null;
                    DataOutputStream dos = null;
                    DataInputStream inStream = null;

                    String exsistingFileName = savedImagePath;
                    String lineEnd = "\r\n";
                    String twoHyphens = "--";
                    String boundary = "*****";

                    int bytesRead, bytesAvailable, bufferSize;
                    byte[] buffer;
                    int maxBufferSize = 1024 * 1024;

                    String urlString = "https://mysite.com/upload.php";
                    float currentRating = ratingbar.getRating();

                    File file = new File(savedImagePath);
                    int sentBytes = 0;
                    long fileSize = file.length();


                    try {
                        // ------------------ CLIENT REQUEST

                        // open a URL connection to the Servlet
                        URL url = new URL(urlString);
                        // Open a HTTP connection to the URL
                        conn = (HttpURLConnection) url.openConnection();
                        // Allow Inputs
                        conn.setDoInput(true);
                        // Allow Outputs
                        conn.setDoOutput(true);
                        // Don't use a cached copy.
                        conn.setUseCaches(false);
                        // Use a post method.
                        conn.setRequestMethod("POST");
                        conn.setRequestProperty("Connection", "Keep-Alive");
                        conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);


                        dos = new DataOutputStream(conn.getOutputStream());



                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                                        + exsistingFileName + "\"" + lineEnd);


                        dos.writeBytes(lineEnd);

                        FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName));
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        buffer = new byte[bufferSize];

                        // read file and write it into form...
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                        while (bytesRead > 0) {
                            dos.write(buffer, 0, bufferSize);

                            // Update progress dialog
                            sentBytes += bufferSize;
                            publishProgress((int)(sentBytes * 100 / fileSize));

                            bytesAvailable = fileInputStream.available();
                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                        }

                        // send multipart form data necesssary after file data...
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                        dos.flush();
                        dos.close();
                        fileInputStream.close();
                    }catch (MalformedURLException e) {

                    }catch (IOException e) {

                    }


                    // ------------------ read the SERVER RESPONSE
                    try {
                        inStream = new DataInputStream(conn.getInputStream());

                        // try to read input stream
                        // InputStream content = inStream.getContent();
                        BufferedInputStream bis = new BufferedInputStream(inStream);
                        ByteArrayBuffer baf = new ByteArrayBuffer(20);

                        long total  = 0;
                        int current = 0;
                        while ((current = bis.read()) != -1) {
                        baf.append((byte) current);



                        /* Convert the Bytes read to a String. */
                        String mytext = new String(baf.toByteArray());
                        final String newtext = mytext.trim();

                        inStream.close();



                    } catch (Exception e) {

                    }
                }
                return msg;
        }



}

5 个答案:

答案 0 :(得分:11)

这应该有效!

connection = (HttpURLConnection) url_stripped.openConnection();
        connection.setRequestMethod("PUT");
        String boundary = "---------------------------boundary";
        String tail = "\r\n--" + boundary + "--\r\n";
        connection.addRequestProperty("Content-Type", "image/jpeg");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Length", ""
                + file.length());
        connection.setDoOutput(true);

        String metadataPart = "--"
                + boundary
                + "\r\n"
                + "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
                + "" + "\r\n";

        String fileHeader1 = "--"
                + boundary
                + "\r\n"
                + "Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
                + fileName + "\"\r\n"
                + "Content-Type: application/octet-stream\r\n"
                + "Content-Transfer-Encoding: binary\r\n";

        long fileLength = file.length() + tail.length();
        String fileHeader2 = "Content-length: " + fileLength + "\r\n";
        String fileHeader = fileHeader1 + fileHeader2 + "\r\n";
        String stringData = metadataPart + fileHeader;

        long requestLength = stringData.length() + fileLength;
        connection.setRequestProperty("Content-length", ""
                + requestLength);
        connection.setFixedLengthStreamingMode((int) requestLength);
        connection.connect();

        DataOutputStream out = new DataOutputStream(
                connection.getOutputStream());
        out.writeBytes(stringData);
        out.flush();

        int progress = 0;
        int bytesRead = 0;
        byte buf[] = new byte[1024];
        BufferedInputStream bufInput = new BufferedInputStream(
                new FileInputStream(file));
        while ((bytesRead = bufInput.read(buf)) != -1) {
            // write output
            out.write(buf, 0, bytesRead);
            out.flush();
            progress += bytesRead;
            // update progress bar
            publishProgress(progress);
        }

        // Write closing boundary and close stream
        out.writeBytes(tail);
        out.flush();
        out.close();

        // Get server response
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream()));
        String line = "";
        StringBuilder builder = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }

参考:http://delimitry.blogspot.in/2011/08/android-upload-progress.html

答案 1 :(得分:2)

你可以这样做:

try { // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(
                    sourceFile);
            URL url = new URL("http://10.0.2.2:9090/plugins/myplugin/upload");
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploadedfile", filename);
            // conn.setFixedLengthStreamingMode(1024);
            // conn.setChunkedStreamingMode(1);
            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                    + filename + "\"" + lineEnd);
            dos.writeBytes(lineEnd);
            bytesAvailable = fileInputStream.available();
            bufferSize = (int) sourceFile.length()/200;//suppose you want to write file in 200 chunks
            buffer = new byte[bufferSize];
            int sentBytes=0;
            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                // Update progress dialog
                sentBytes += bufferSize;
                publishProgress((int)(sentBytes * 100 / bytesAvailable));
                bytesAvailable = fileInputStream.available();
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }
            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();
            // close streams
            fileInputStream.close();
            dos.flush();
            dos.close();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

答案 2 :(得分:2)

我有同样的问题,这对我有帮助。这对你也有帮助。

在Async任务类中,编写(粘贴)以下代码。

    ProgressDialog dialog;

    protected void onPreExecute(){
        //example of setting up something
        dialog = new ProgressDialog(your_activity.this);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setMax(100);
        dialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        for (int i = 0; i < 20; i++) {
            publishProgress(5);
            try {
                Thread.sleep(88);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        dialog.dismiss();
        return null;
    }
    protected void onProgressUpdate(Integer...progress){
        dialog.incrementProgressBy(progress[0]);
    }

如果发生错误,请从代码中删除"publishProgress(5);"。否则很高兴。

答案 3 :(得分:0)

您需要对浮点值进行除法并将结果转换回int:

float progress = ((float)sentBytes/(float)fileSize)*100.0f;
publishProgress((int)progress);

答案 4 :(得分:0)

我花了两天with this example

这一切都在这个字符串中。

conn.setRequestProperty("ENCTYPE", "multipart/form-data");

只有它有帮助。