Skip to content

Instantly share code, notes, and snippets.

@vuhung3990
Last active December 3, 2021 22:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vuhung3990/0a90c0d2fd633800301d to your computer and use it in GitHub Desktop.
Save vuhung3990/0a90c0d2fd633800301d to your computer and use it in GitHub Desktop.
background upload with progress
package com.grasys.shortupload.helper;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by VuHung on 1/16/2015.
*/
public class BackgroundUploader extends AsyncTask<Void, Integer, Void> implements DialogInterface.OnCancelListener {
private final Context context;
private ProgressDialog progressDialog;
private String url;
private File file;
public BackgroundUploader(Context context,String url, File file) {
this.url = url;
this.file = file;
this.context = context;
}
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Uploading...");
progressDialog.setCancelable(false);
progressDialog.setMax((int) file.length());
progressDialog.show();
}
@Override
protected Void doInBackground(Void... v) {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection connection = null;
String fileName = file.getName();
try {
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("PUT");
String boundary = "---------------------------boundary";
String tail = "\r\n--" + boundary + "--\r\n";
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setDoOutput(true);
String metadataPart = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
+ "" + "\r\n";
String fileHeader1 = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
+ fileName + "\"\r\n"
+ "Content-Type: application/octet-stream\r\n"
+ "Content-Transfer-Encoding: binary\r\n";
long fileLength = file.length() + tail.length();
String fileHeader2 = "Content-length: " + fileLength + "\r\n";
String fileHeader = fileHeader1 + fileHeader2 + "\r\n";
String stringData = metadataPart + fileHeader;
long requestLength = stringData.length() + fileLength;
connection.setRequestProperty("Content-length", "" + requestLength);
connection.setFixedLengthStreamingMode((int) requestLength);
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(stringData);
out.flush();
int progress = 0;
int bytesRead = 0;
byte buf[] = new byte[1024];
BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(file));
while ((bytesRead = bufInput.read(buf)) != -1) {
// write output
out.write(buf, 0, bytesRead);
out.flush();
progress += bytesRead;
// update progress bar
publishProgress(progress);
}
// Write closing boundary and close stream
out.writeBytes(tail);
out.flush();
out.close();
// Get server response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (Exception e) {
// Exception
e.printStackTrace();
} finally {
if (connection != null) connection.disconnect();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
progressDialog.setProgress((int) (progress[0]));
}
@Override
protected void onPostExecute(Void v) {
System.out.println("SUCCESS");
progressDialog.setMax(0);
progressDialog.setProgress(0);
progressDialog.dismiss();
}
@Override
public void onCancel(DialogInterface dialog) {
cancel(true);
dialog.dismiss();
}
}
@adihanifsdr
Copy link

Many thanks!

@zal-byte
Copy link

zal-byte commented Dec 3, 2021

wow, this is amazing, thank you so much !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment