上传图片时获得进度

时间:2017-01-09 11:53:46

标签: android server image-uploading

我希望在将任何图片上传到服务器时取得进展。像1%,30%等 我使用了已在不同网站上提供的所有解决方案,但我在DataOutputStream的写作中阅读文件取得了进展。

实施例。

   while (bytesRead > 0) {
                        dos.write(buffer, 0, bufferSize);
                        sentBytes += bufferSize;
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        if (bytesAvailable > 0) {
                            float progress = ((float) sentBytes / (float) totalAvailable) * 100.0f;
                            if (progress % 10 == 0) {
                                publishProgress(sourceFile, (int) progress);
                            }
                        } else {
                            publishProgress(sourceFile, 100);
                        }
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    }

我立刻得到100%。但是在获得100%之后它还在这一行上传图像:

        /*Responses from the server (code and message)*/
            int serverResponseCode = conn.getResponseCode();

我认为只有这一行才负责上传图片。 那么我怎样才能获得实际的服务器上传进度。

服务器端是否有任何要求? 我的服务器支持

 connection.setRequestProperty("Content-Type", "application/octet-stream");

请帮帮我。感谢

2 个答案:

答案 0 :(得分:2)

检查此处提供的答案:

您的图片也是一个文件,要清楚。

直接来源指南:

答案 1 :(得分:0)

我使用了以下方法:

这里publishProgress()将更新progressBar。

public String uploadFileWithProgress(String fileName, String serverUrl) {
    Lg.info(DEBUG_TAG, "uploadFile fileName:" + fileName);
    Lg.info(DEBUG_TAG, "uploadFile" + "serverUrl: " + serverUrl);

    HttpURLConnection conn = null;

    File sourceFile = new File(fileName);

    String response = null;

    Lg.info(DEBUG_TAG, "sourceFile: " + sourceFile.toString());

    if (!sourceFile.isFile()) {
    } else {

        HttpURLConnection.setFollowRedirects(false);
        try {

            FileInputStream fileInputStream = new FileInputStream(sourceFile);

            conn = (HttpURLConnection) new URL(serverUrl).openConnection();
            conn.setRequestMethod("PUT");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            conn.setRequestProperty("Accept", "application/json");


            conn.setReadTimeout(100000);
            conn.setConnectTimeout(100000);

            //required --->
            conn.setDoOutput(true);

            long fileLength = sourceFile.length();

            long requestLength = fileLength;
            conn.setRequestProperty("Content-length", "" + requestLength);
            conn.setFixedLengthStreamingMode((int) requestLength);
            conn.connect();
            //<-----

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

            int progress = 0;
            int bytesRead = 0;
            byte buf[] = new byte[1024];
            BufferedInputStream bufInput = new BufferedInputStream(fileInputStream);
            publishProgress(sourceFile, 0);
            lastProgressDone = 0;
            while ((bytesRead = bufInput.read(buf)) != -1) {
                // write output
                out.write(buf, 0, bytesRead);
                out.flush();
                progress += bytesRead;
                // update progress bar
                int progressDoneInPercentage = (int) (progress * 100.0 / requestLength);

                if (progressDoneInPercentage < 100 && progressDoneInPercentage != lastProgressDone) {
                    lastProgressDone = progressDoneInPercentage;
                    publishProgress(sourceFile, progressDoneInPercentage);
                }
            }

            fileInputStream.close();
            // Write closing boundary and close stream
            try {
                out.flush();
            } catch (Exception e) {
            }
            try {
                out.close();
            } catch (Exception e) {
            }

            /*Responses from the server (code and message)*/
            int serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            lastProgressDone = 0;
            if (serverResponseCode == 200) {
                publishProgress(sourceFile, 100);
            } else {
                publishProgress(sourceFile, 0);
            }
            InputStream str = conn.getErrorStream();
            Lg.info(DEBUG_TAG, "uploadFile HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
            if (serverResponseCode == 200) {
                Lg.info(DEBUG_TAG, "uploadFile uploadComplete: " + response);
            } else{
                Lg.info(DEBUG_TAG, "uploadFile Error" + response);
            }

        } catch (OutOfMemoryError e) {
            Lg.printStackTrace(e);
        } catch (Exception e) {
            // Exception
            Lg.error("error in image uploading = " + fileName, e.getMessage());
        } finally {
            if (conn != null) conn.disconnect();
        }
    }
    return response;
}