I need to upload a large generated pdf file to the server and show uploading progress to the user. But the problem is the percentage I got from OutputStream is not the real progress because after 100% progress of OutputStream, still cannot get response code from the server (need to wait for more)
Please help me with this problem. Thank you.
** For more information: the total uploading time is 15 minutes but the progress percentage finish in a second.
class UploadPdf extends AsyncTask<String, Integer, String> {
private Activity activity;
private String orderId = "";
private String filenamepdf = "";
private String filenamezip = "";
private int dpi = 640;
public ImageCreator mImageCreator;
public UploadPdf(Activity activity) {
this.activity = activity;
}
@Override
protected String doInBackground(String... strings) {
orderId = strings[0];
filenamepdf = orderId + ".pdf";
String uploadStatus = uploadFileToServer();
return uploadStatus;
}
@Override
protected void onProgressUpdate(Integer... progress) {
//Update progress
updateProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {
//Show result
try {
JSONObject obj = new JSONObject(result);
if(obj.getString("status").equals("success")) {
uploadSuccess();
} else {
errorContainer.setVisibility(View.VISIBLE);
}
} catch (Exception ex) {
errorContainer.setVisibility(View.VISIBLE);
}
}
private String uploadFileToServer() {
Log.d(LOGTAG, "uploadFileToServer");
String urlString = Constants.API_BASE_URL + Constants.API_CREATE_UPLOAD_FILE;
String response = null;
String attachmentName = "attachment";
String attachmentFileName = "attachment";
String crlf = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
File file = new File(filenamepdf);
MultipartUtility multipart = new MultipartUtility(urlString, "UTF-8", getApplicationContext());
multipart.addFormField("order_id", orderId);
multipart.addFilePart("album_image_path", file);
List<String> responseReturn = multipart.finish();
Log.e(LOGTAG, "SERVER REPLIED:");
response = "";
for (String line : responseReturn) {
Log.e(LOGTAG, "Upload Files Response:::" + line);
response += line;
}
} catch (Exception ex) {
Log.e(LOGTAG, "Failed:" + ex.getMessage());
}
Log.e(LOGTAG, "Response:" + response);
return response;
}
public class MultipartUtility {
private final String LOGTAG = "MultipartUtility";
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
Context context;
/**
* This constructor initializes a new HTTP POST request with content type
* is set to multipart/form-data
*
* @param requestURL
* @param charset
* @throws IOException
*/
public MultipartUtility(String requestURL, String charset, Context context)
throws IOException {
this.charset = charset;
this.context = context;
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
/**
* Adds a form field to the request
*
* @param name field name
* @param value field value
*/
public void addFormField(String name, String value) {
Log.d(LOGTAG, "name: " + name + ", value: " + value);
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
/**
* Adds a upload file section to the request
*
* @param fieldName name attribute in <input type="file" name="..." />
* @param uploadFile a File to be uploaded
* @throws IOException
*/
public void addFilePart(String fieldName, File uploadFile) throws IOException {
String fileName = uploadFile.getName();
Log.d(LOGTAG, fieldName);
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] bytes = new byte[(int) uploadFile.length()];
int byteLength = bytes.length;
byte[] buffer = new byte[4096];
int bytesRead = -1;
int sendByte = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
sendByte += bytesRead;
int progress = (int)(sendByte / (float) byteLength * 100);
Log.d(LOGTAG, "bytesRead: " + bytesRead + ", byteLength: " + byteLength + ", progress: " + progress);
publishProgress(progress);
}
outputStream.flush();
Log.d(LOGTAG, "Read byte finish");
outputStream.close();
Log.d(LOGTAG, "Close output stream");
inputStream.close();
Log.d(LOGTAG, "Close input stream");
writer.append(LINE_FEED);
writer.flush();
Log.d(LOGTAG, "Writer flushed");
}
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}
public List<String> finish() throws IOException {
Log.d(LOGTAG, "Finishing");
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
Log.d(LOGTAG, "Line feed flushed");
writer.append("--" + boundary + "--").append(LINE_FEED);
Log.d(LOGTAG, "Last line flushed");
writer.close();
Log.d(LOGTAG, "Writer closed");
// checks server's status code first
int status = httpConn.getResponseCode();
Log.d(LOGTAG, "Server returned status: " + status);
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
}
}