我正在開發一個應用程序,允許用戶上傳媒體文件(如圖片,照片,視頻)到服務器,我有一個大的文件有點問題 - 太長等待並查看活動進度條,同時其上傳和另一個問題 - 如果應用程序死亡上傳死亡,所以我需要將我的上傳代碼轉移到服務。所以在這裏我的麻煩開始了 - 如果我將我的上傳代碼傳輸到服務器,我如何發送進度更新(%)到活動?上傳文件到服務器的背景
,這裏是我上傳的方法的代碼:
public static void uploadMovie(final HashMap<String, String> dataSource, final OnResponseListener finishedListener, final ProgressListener progressListener) {
if (finishedListener != null) {
new Thread(new Runnable() {
public void run() {
try {
//Prepare data-->
String boundary = getMD5(dataSource.size() + String.valueOf(System.currentTimeMillis()));
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.setCharset(Charset.forName("UTF-8"));
for (String key : dataSource.keySet()) {
if (key.equals(MoviesFragmentAdd.USERFILE)) {
FileBody userFile = new FileBody(new File(dataSource.get(key)));
multipartEntity.addPart(key, userFile);
continue;
}
multipartEntity.addPart(key, new StringBody(dataSource.get(key), ContentType.APPLICATION_JSON));
}
HttpEntity entity = multipartEntity.build();
//<--
//Prepare Connection-->
trustAllHosts();
HttpsURLConnection conn = (HttpsURLConnection) new URL(SAKH_URL_API + "/video/addForm/").openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("Content-length", entity.getContentLength() + "");
conn.setRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());
conn.connect();
//<--
// Upload-->
OutputStream os = conn.getOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
entity.writeTo(baos);
baos.close();
byte[] payload = baos.toByteArray();
baos = null;
int totalSize = payload.length;
int bytesTransferred = 0;
int chunkSize = 2000;
while (bytesTransferred < totalSize) {
int nextChunkSize = totalSize - bytesTransferred;
if (nextChunkSize > chunkSize) {
nextChunkSize = chunkSize;
}
os.write(payload, bytesTransferred, nextChunkSize);
bytesTransferred += nextChunkSize;
//Progress update-->
if (progressListener != null) {
progressListener.onProgressUpdate((100 * bytesTransferred/totalSize));
}
//<--
}
os.flush();
//<--
//Get server response-->
int status = conn.getResponseCode();
if (conn.getResponseCode() == HttpsURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
JsonObject request = (JsonObject) gparser.parse(in.readLine());
if (!request.get("error").getAsBoolean()) {
finishedListener.onLoadFinished(new Object());
}
} else {
throw new IOException("Server returned non-OK status: " + status);
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
finishedListener.onNotConnected();
}
}
}).start();
}
}
十分感謝您的回答,我會嘗試,因爲你寫的。 – whizzzkey
不客氣。此外,請記住,當您的服務正在下載東西或設備可以進入睡眠模式時進行電源鎖定。 – Gusman