簡體   English   中英

使用DataOutputStream上傳文件不會顯示實際進度

[英]uploading a file with DataOutputStream doesn't display real progress

我正在使用DataOutputStream通過以下代碼將文件從android上傳到我的網絡服務器:

public class SnapshotUploadTask extends AsyncTask<Object, Integer, Void> {

    private final File file;
    private final ProgressDialog progressDialog;
    private final Activity activity;

    public SnapshotUploadTask(File file, ProgressDialog progressDialog, Activity activity) {
        this.progressDialog = progressDialog;
        this.file = file;
        this.activity = activity;
    }

    @Override
    protected void onPreExecute() {
        progressDialog.setProgress(0);
    }

    @Override
    protected Void doInBackground(Object... arg0) {

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

        int bytesRead;
        int bytesAvailable;
        int bufferSize;

        byte[] buffer;

        int maxBufferSize = 1 * 512;

        try {

            FileInputStream fileInputStream = new FileInputStream(file);
            URL url = new URL("http://bla.bla.bla/upload");

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("uploaded_file", file.getName());

            DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());

            dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
            dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + file.getName() + "\"" + lineEnd);

            dataOutputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            final int hundredPercent = bytesAvailable;
            progressDialog.setMax(hundredPercent);

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                dataOutputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                final int restBytes = bytesAvailable;
                final int uploadedBytes = hundredPercent - restBytes;

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.setProgress((int) uploadedBytes);
                        if (restBytes <= 0) {
                            progressDialog.setMessage(activity.getString(R.string.camera_uploading_done));
                        }
                    }
                });
             }

            dataOutputStream.writeBytes(lineEnd);
            dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            if (serverResponseCode == 200) {
                progressDialog.dismiss();
            }

            fileInputStream.close();
            dataOutputStream.flush();
            dataOutputStream.close();

        } catch (Exception e) {
            progressDialog.dismiss();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        progressDialog.dismiss();
    }
}

現在發生的事情是,一旦我在OutputStream中寫入了一定數量的字節,便立即更新我的progressDialog,這導致ProgressDialog在服務器實際接收到數據之前達到100%。

我僅在到達connection.getResponseCode();時才知道傳輸完成的時間connection.getResponseCode();

我想要的是在服務器實際接收到數據塊時更新進度。 有沒有辦法做到這一點?

您需要知道HttpURLConnection緩沖所有輸出,除非您設置固定長度或分塊傳輸模式,您一定要這樣做,而不是自己實現它。 這樣可以正確設置Content-Length標頭。 如果您使用這些傳輸模式之一,則沒有緩沖。

注意:您正在濫用available() :請參閱Javadoc; 在大多數情況下,您正在編寫垃圾郵件:

dataOutputStream.write(buffer, 0, bufferSize);

應該

dataOutputStream.write(buffer, 0, bytesRead);

您也不需要在讀取循環內擺弄available() 這樣的事情就足夠了:

long total = 0;
int maxBufferSize = 8192; // at least. 512 is far too small.
while ((bytesRead = fileInputStream.read(buffer, 0, bufferSize)) > 0) {
    dataOutputStream.write(buffer, 0, bytesRead);
    total += bytesRead;
    final long uploadedBytes = total;

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            progressDialog.setProgress(uploadedBytes);
                }
        });
    }
}
// at this point we are at end of stream
activity.runOnUiThread(new Runnable() {
    @Override
    public void run() {
progressDialog.setMessage(activity.getString(R.string.camera_uploading_done));
    }
}

E&OE

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM