当我上传超过 5MB 的文件时,进度条会在达到 4% 时自行重置,并且每 10 秒从 0 开始。但是,对于 5MB 以下的文件,进度条可以正常工作并达到 100%
这是因为maxBufferSize
? 服务器最大帖子大小为 512MB,其他一切都是无限的,所以问题一定出在我的代码上,但我不确定在哪里。
这是我的代码
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
//update Dialog box progress
mProgressDialog.setProgress(progress[0]);
if ( nofti_appended )
{
//update Notification progress
mBuilder.setProgress(100, progress[0], false);
}
}
protected String doInBackground(String... urls) {
String upLoadServerUri = upApi.uploadUrl;
String fileName = this.file_path;
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
File sourceFile = new File(fileName);
int sentBytes = 0;
long fileSize = sourceFile.length();
try
{
FileInputStream fileInputStream = new FileInputStream(new File(fileName));
URL url = new URL(upLoadServerUri);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(1024);
// 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=\"file[]\";filename=\""+ fileName + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
Log.v("Size",bytesAvailable+"");
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
if(isCancelled()){
break;
}
sentBytes += bytesRead;
publishProgress((int)(sentBytes * 100 / fileSize));
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
if(isCancelled()){
return "faild";
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
Scanner s;
s = new Scanner(connection.getInputStream());
s.useDelimiter("\\Z");
final String response = s.next();
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
fileInputStream.close();
outputStream.flush();
outputStream.close();
if(serverResponseCode == 200)
{
return response;
}
} catch (MalformedURLException ex) {
} catch (final Exception e) {
}
return "faild";
}
有任何想法吗?