如何在使用百分比上传时显示进度条

时间:2016-01-29 04:37:46

标签: android progress-bar video-processing

我正在上传视频和照片。它的工作正常。现在我想用百分比上传数据时显示进度条。我从android hive参考并在 httpclient 中实现并修改了它因此 httpurlconnection 。任何帮助都会感激。谢谢。

这是异步任务执行的主要活动。

protected void onProgressUpdate(Integer... progress) {
        // Making progress bar visible
        progressBar.setVisibility(View.VISIBLE);

        // updating progress bar value
        progressBar.setProgress(progress[0]);

        // updating percentage value
        txtPercentage.setText(String.valueOf(progress[0]) + "%");
    }

    @Override
    protected String doInBackground(Void... params) {
        return uploadFile();
    }

    @SuppressWarnings("deprecation")
    private String uploadFile() {
        String responseString = null;
            String charset = "UTF-8";
            String requestURL = "YOUR_URL";

            VideoUpload multipart = null;
            try {
                multipart = new VideoUpload(Config.FILE_UPLOAD_URL, charset);
            } catch (IOException e) {
                e.printStackTrace();
            }

        {
            //========================================================
            AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                    new AndroidMultiPartEntity.ProgressListener() {

                        @Override
                        public void transferred(long num) {
                            publishProgress((int) ((num / (float) totalSize) * 100));
                        }
                    });
            //========================================================
            multipart.addFormField("website", "www.androidhive.info");
            multipart.addFormField("email", "abc@gmail.com");
            try {
                multipart.addFilePart("image", new File(filePath));
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                List<String> response = multipart.finish(); // response from server.
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        Log.e(TAG, "Response from server: " + result);

        // showing the server response in an alert dialog
        showAlert(result);

        super.onPostExecute(result);
    }

}

这是我对httpurlconnections及其工作的升级课程。

public VideoUpload(String requestURL, String charset)
        throws IOException {
    this.charset = charset;

    // creates a unique boundary based on time stamp
    boundary = "===" + System.currentTimeMillis() + "===";

    URL url = new URL(requestURL);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true); // indicates POST method
    httpConn.setDoInput(true);
    httpConn.setRequestProperty("Content-Type",
            "multipart/form-data; boundary=" + boundary);
    httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
    httpConn.setRequestProperty("Test", "Bonjour");
    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
            true);
}

/**
 * Adds a form field to the request
 *
 * @param name  field name
 * @param value field value
 */
public void addFormField(String name, String value) {
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
            .append(LINE_FEED);
    writer.append("Content-Type: text/plain; charset=" + charset).append(
            LINE_FEED);
    writer.append(LINE_FEED);
    writer.append(value).append(LINE_FEED);
    writer.flush();
}

/**
 * Adds a upload file section to the request
 *
 * @param fieldName  name attribute in <input type="file" name="..." />
 * @param uploadFile a File to be uploaded
 * @throws IOException
 */
public void addFilePart(String fieldName, File uploadFile)
        throws IOException {
    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append(
            "Content-Disposition: form-data; name=\"" + fieldName
                    + "\"; filename=\"" + fileName + "\"")
            .append(LINE_FEED);
    writer.append(
            "Content-Type: "
                    + URLConnection.guessContentTypeFromName(fileName))
            .append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
    outputStream.flush();
    inputStream.close();

    writer.append(LINE_FEED);
    writer.flush();
}

/**
 * Adds a header field to the request.
 *
 * @param name  - name of the header field
 * @param value - value of the header field
 */
public void addHeaderField(String name, String value) {
    writer.append(name + ": " + value).append(LINE_FEED);
    writer.flush();
}

/**
 * Completes the request and receives response from the server.
 *
 * @return a list of Strings as response in case the server returned
 * status OK, otherwise an exception is thrown.
 * @throws IOException
 */
public List<String> finish() throws IOException {
    List<String> response = new ArrayList<String>();

    writer.append(LINE_FEED).flush();
    writer.append("--" + boundary + "--").append(LINE_FEED);
    writer.close();

    // checks server's status code first
    int status = httpConn.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpConn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            response.add(line);
        }
        reader.close();
        httpConn.disconnect();
    } else {
        throw new IOException("Server returned non-OK status: " + status);
    }

    return response;
}

这里我从androidhive学习了进度栏课程,但我不知道如何使用它

public class AndroidMultiPartEntity extends MultipartEntity

 {

private final ProgressListener listener;

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

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

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

2 个答案:

答案 0 :(得分:3)

There is progressUpdate method in AsyncTask class, which will return you progress of file uploading, here is my code which might help you out.

private final ProgressDialog mDialog;

mDialog = new ProgressDialog(context);
        mDialog.setMax(100);
        mDialog.setMessage("Uploading " + file.getName());
        mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mDialog.setProgress(0);
        mDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // This will cancel the putFile operation
                mRequest.abort();
            }
        });
        mDialog.show();

@Override
    protected void onProgressUpdate(Long... progress) {
        int percent = (int)(100.0*(double)progress[0]/mFileLen + 0.5);
        mDialog.setProgress(percent);
    }

答案 1 :(得分:1)

使用此代码,对于文件上传

,这对我来说非常有用
public class MultipartUtility {

    FileUploadListener listener;
    private static final int BUFFER_SIZE = 1024;
    private static final int TIME_OUT = 3 * 60 * 1000;
    private final String boundary;
    private static final String LINE_FEED = "\r\n";
    private HttpURLConnection httpConn;
    private String charset;
    private OutputStream outputStream;
    private PrintWriter writer;
    public int statusCode;
    public String mURL;

    public interface FileUploadListener {
        void onUpdateProgress(int percentage, long kb);

        boolean isCanceled();
    }

    /**
     * This constructor initializes a new HTTP POST request with content type
     * is set to multipart/form-data
     *
     * @param requestURL
     * @param charset
     * @throws IOException
     */
    public MultipartUtility(String requestURL, String charset, FileUploadListener listener)
            throws IOException {
        this.charset = charset;
        this.listener = listener;
        mURL = requestURL;
        // creates a unique boundary based on time stamp
        boundary = "" + System.currentTimeMillis() + "";

        URL url = new URL(requestURL);
        httpConn = null;
        if (url.getProtocol().toLowerCase().equals("https")) {
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            https.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            httpConn = https;
        } else {
            httpConn = (HttpURLConnection) url.openConnection();
        }

        // httpConn.setConnectTimeout(TIME_OUT);
        //httpConn.setReadTimeout(TIME_OUT);
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setChunkedStreamingMode(BUFFER_SIZE);
        httpConn.setRequestMethod("POST");
        httpConn.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + boundary);
        httpConn.setRequestProperty("Connection", "Keep-Alive");
        outputStream = httpConn.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
                true);
    }

    private static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
        }};

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * Adds a form field to the request
     *
     * @param name  field name
     * @param value field value
     */
    public void addFormField(String name, String value) {
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
                .append(LINE_FEED);
        writer.append("Content-Type: text/plain; charset=" + charset).append(
                LINE_FEED);
        writer.append(LINE_FEED);
        writer.append(value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Adds a upload file section to the request
     *
     * @param fieldName name attribute in <input type="file" name="..." />
     * @param uploadFile a File to be uploaded
     * @throws IOException
     */
    private long lastProgressUpdateTime = 0;

    public void addFilePart(String fieldName, File uploadFile)
            throws IOException {
        String fileName = uploadFile.getName();
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append(
                "Content-Disposition: form-data; name=\"" + fieldName
                        + "\"; filename=\"" + fileName + "\"")
                .append(LINE_FEED);
        writer.append(
                "Content-Type: "
                        + URLConnection.guessContentTypeFromName(fileName))
                .append(LINE_FEED);
        writer.append("charset=" + charset).append(
                LINE_FEED);
        writer.append(LINE_FEED);
        writer.flush();

        outputStream.flush();
        byte[] buffer = new byte[BUFFER_SIZE];

        try {
            final FileInputStream inputStream = new FileInputStream(uploadFile);
            long totalRead = 0;
            long totalSize = uploadFile.length();

            int read;
            while ((read = inputStream.read(buffer)) > 0) {
                totalRead += read;
                int percentage = (int) ((totalRead / (float) totalSize) * 100);
                outputStream.write(buffer, 0, read);

                long now = System.currentTimeMillis();
                if (lastProgressUpdateTime == 0 || lastProgressUpdateTime < now - 100) {
                    lastProgressUpdateTime = now;

                    Log.e("", totalRead + " " + " " + percentage);

                    if (listener != null)
                        this.listener.onUpdateProgress(percentage, totalRead);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            outputStream.flush();
        }

        writer.append(LINE_FEED);
        writer.flush();
    }


    /**
     * Adds a header field to the request.
     *
     * @param name  - name of the header field
     * @param value - value of the header field
     */
    public void addHeaderField(String name, String value) {
        writer.append(name + ": " + value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Completes the request and receives response from the server.
     *
     * @return a list of Strings as response in case the server returned
     * status OK, otherwise an exception is thrown.
     * @throws IOException
     */
    public String Execute() throws IOException {
        String responses = "";

        writer.append(LINE_FEED).flush();
        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();
        StringBuilder sb = new StringBuilder();
        try {
            // checks server's status code first
            statusCode = httpConn.getResponseCode();
            if (Constants.IS_DEBUG) {
                Log.v(Constants.TAG, "Url: " + mURL);
                Log.e("", "response code :" + statusCode);
            }
            //responses = ;

            sb.append("" + Utility.convertStreamToString(httpConn.getInputStream()) + "\n");

            if (statusCode == HttpURLConnection.HTTP_OK) {
                httpConn.disconnect();
            }
            responses = sb.toString();
            Log.v(Constants.TAG, " response: " + responses);
            return responses;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            sb = new StringBuilder();

            sb.append("" + Utility.convertStreamToString(httpConn.getErrorStream()) + "\n");

            responses = sb.toString();
            Log.v(Constants.TAG, "Error response: " + responses);
        }
        return responses;
    }
}

并以这种方式打电话

   MultipartUtility multipart = new MultipartUtility(API.URL , "UTF-8", 
                        new  MultipartUtility.FileUploadListener() {

                            @Override
                            public void onUpdateProgress(final int percentage, final long kb) {

                            Activity.this.runOnUiThread(new Runnable() {

                               @Override
                               public void run() {
                                //  your progress code


                                 }});
                            }

                            @Override
                            public boolean isCanceled() {
                                // Canceled or not
                                return false;
                            }
                        });


                        multipart.addFormField("zipFileName", mFile.getName());

                        multipart.addFilePart("file", mFile);

                        String response = multipart.Execute(); 
相关问题