我有一个异步任务,应该在文件上传期间显示进度。一切正常,只是它看起来真的非常快地完成了文件上传,然后它就坐在那里 100% 等待。
我将其追溯到
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"Filedata\";filename=\"" + pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
long totalBytesWritten = 0;
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
outputStream.flush();
if (mCancel) { throw new CancelException(); }
totalBytesWritten += bufferSize;
if (mProgressDialog != null) {
mProgressDialog.setProgress(Integer.valueOf((int) (totalBytesWritten / 1024L)));
}
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
我注意到的是,直到它获取响应代码的最后一行之前没有真正的延迟。我认为正在发生的事情是数据正在缓冲,所以看起来它已经上传了它,但实际上并没有 - 它只是缓冲了它。然后当我调用 getResponseCode() 时,它别无选择,只能完成上传以获取上传状态。有什么方法可以让它实际上传,这样我才能得到合理的进展?