我在 google 和 stackoverflow 上搜索了很多次,但我找不到我真正需要的东西。我编写了一个使用 asynctask 方法将文件上传到服务器的代码。我所做的是:在 asyntask 方法中,我使用post方法将我的文件上传到我的webservice。在doInBackground方法中:
int serverResponseCode = 0;
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
// ------------------ CLIENT REQUEST
URL url = new URL(upLoadServerUri);
// 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
// Use a post method.
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("file_name", fileName);
conn.setRequestProperty("file_name_audio", fileName);
// conn.setFixedLengthStreamingMode(1024);
// conn.setChunkedStreamingMode(1);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file_name\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
int streamSize = (int) sourceFile.length();
bufferSize = streamSize / 4;
buffer = new byte[streamSize];
int sentBytes=0;
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
Thread.sleep(2);
sentBytes += bufferSize;
int progress = (int)((sentBytes / (float) bytesAvailable) * 100);
publishProgress( progress+"");
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
// bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// 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();
@SuppressWarnings("unused")
String serverResponseMessage = conn.getResponseMessage();
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
}
String serverResponseMessage = conn.getResponseMessage();更长的时间
我的uploadprogress设置了4次,然后我等待更多时间将我的文件真正上传到服务器。为什么如果代码退出我需要。while
如何设置progressbar值更敏感,当progressbar
值设置为100时,我想要文件上传真的完成。我设置了 onpreexecute 和 onpostexecute 方法。但我认为他们没有必要在这里写。我使用notificationbar
进度,所以我必须显示百分比。