如何在Android中使用MultipartEntityBuilder上传文件时显示进度条?

时间:2017-07-01 07:53:36

标签: java android progressdialog

我希望在使用MultipartEntityBuilder上传文件和其他字符串数据时显示进度对话框(带百分比)。目前我使用以下代码:

try {

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            if (!src.equals(""))
                builder.addPart("myFile", fb);
            builder.addPart("list", new StringBody(list, ContentType.TEXT_PLAIN));
            HttpEntity entity = builder.build();

            URL url = new URL(FILE_UPLOAD_URL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("token", sharedpreferences.getString("token", ""));
            conn.setRequestProperty("app_version", app_version);
            conn.setRequestProperty("api_version", api_version);
            conn.setRequestMethod("POST");
            conn.addRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            //conn.connect();

            long len = entity.getContentLength();
            Log.v("Full Data Size", "" + len + " B");
            long total = 0;
            int count;

            if (!src.equals("")) {
                InputStream input = new BufferedInputStream(new FileInputStream(file));
                byte data[] = new byte[1024];

                while ((count = input.read(data)) != -1) {
                    total += count;
                    Log.v("total", "" + total);
                    publishProgress((int) ((total * 100) / len));
                }
            }

            entity.writeTo(conn.getOutputStream());

            int responseCode = conn.getResponseCode();
            Log.v("response Code", "" + responseCode);
            Log.v("response error", "" + conn.getErrorStream());
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder("");
                String line = "";
                while ((line = in.readLine()) != null)
                    sb.append(line);
                in.close();
                Log.v("response String", "" + sb);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

任何帮助将不胜感激!!谢谢...

0 个答案:

没有答案