我有一个允许将文件上传到服务器的应用程序。进度条显示上传进度。上传代码如下:
try{
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
int lengthOfFile = (int) sourceFile.length();
URL url = new URL(server_url);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setChunkedStreamingMode(1024); // to prevent crashes due to large files
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("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
int total = 0;
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
total += bytesRead;
publishProgress("" + (int) ((total * 100) / lengthOfFile));
}
// 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();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
// ...
上传效果很好,但是进度条显示了一个怪异的行为:它达到某个值(例如14%),然后返回零,然后再次上升到某个值,依此类推。在某个时候,它只会卡住,直到上传完成并且该栏被取消。我想这与读取文件的方式有关。请注意,如果没有conn.setChunkedStreamingMode(1024);
行,也会发生同样的情况。如何使其正常工作?