Android: updating progressbar for file upload

自闭症网瘾萝莉.ら 提交于 2019-11-29 00:00:15

This should work !

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);
        }

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

You can do like:

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

I had the same problem and this helped me. This can help you too.

In your Async task class, write (paste) the following code.

    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]);
    }

If error occurs, remove "publishProgress(5);" from the code. Otherwise its good to go.

You need to do the division on float values and convert the result back to int:

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

I spend two days with this example.

And all in this string.

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

Only it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!