【发布时间】:2012-03-05 18:49:26
【问题描述】:
使用以下代码实现了文件(图像、文本等)从移动应用程序通过 SIM 卡/WiFi 上传(从移动设备的 SD 卡)到文件服务器位置的功能。
文件上传功能在以下代码中运行良好,这里只有进度对话框的更新是一个问题。
uploadFile() 是从 AsyncTask 的 doInBackground(String... params) 调用的
protected void onProgressUpdate(String... values) 处理进度对话框百分比更新
以下代码负责文件上传
以下代码遇到的问题:
i> 进度对话框以适当的间隔从 0% 更新到 100%,然后等待很长时间,然后返回文件状态(布尔值)。
protected boolean uploadFile(String serverUrl, String filePath) {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int serverResponseCode;
String serverResponseMessage;
boolean uploadstatus = false;
int count;
long lengthOfFile;
try {
FileInputStream fileInputStream;
fileInputStream = new FileInputStream(new File(filePath));
URL url = new URL(serverUrl);
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=\"upload\";filename=\""
+ Utils.getInstance().getFileName(filePath) + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
lengthOfFile = new File(filePath).length();// length of file
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[1024];
bytesRead = 0;
String progressMsg = "";
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
total += bytesRead;
progressMsg = new StringBuffer("").append((int) ((total * 100) / totalLengthOfFile))
.toString();
prgressBarMsg[0] = progressMsg;
publishProgress(prgressBarMsg);
outputStream.write(buffer);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
if (serverResponseCode == 200)// HTTP OK Message from server
{
uploadstatus = true;
} else {
uploadstatus = false;
}
catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
connection.disconnect();
}
return uploadstatus;
}
在我看来,progressdialog 上显示的百分比实际上是从文件(位于 SDCard 上)读取到缓冲区的百分比数据,而不是通过 SIM 从移动设备发送到文件服务器的数据卡/WiFi。进度对话框显示 100% 后的长时间延迟是我担心的原因。
请确认源代码是否显示正确的progressdialog更新方法。此外,水平样式的进度对话框同时显示值 100 % 和 100/100 。
如何去掉100/100的显示?
欢迎任何其他提示/建议。
【问题讨论】:
标签: android