HTTURLConnection Upload not 100% working - java

I am trying to upload a file to a server with following code, the upload works, but the payload is added to the file, you can see it for example uploading a text file:
private Integer doFileUpload(final String urlServer) {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
FileInputStream fileInputStream = null;
final String pathToOurFile = mFileInfo.getProviderPath();
final String lineEnd = "\r\n";
final String twoHyphens = "--";
final String boundary = "*****";
int fileLength;
int bytesToRead, bufferSize;
final long fileSize;
byte[] buffer;
final int maxBufferSize = 1 * 1024 * 1024;
try {
final File file = new File(pathToOurFile);
fileInputStream = new FileInputStream(file);
final URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
final String[] payload = { twoHyphens + boundary + lineEnd,
"Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile + "\"" + lineEnd, lineEnd, lineEnd,
twoHyphens + boundary + twoHyphens + lineEnd };
int payloadLength = 0;
for (final String string : payload) {
payloadLength += string.getBytes("UTF-8").length;
}
Logger.d(AsyncEgnyteUploadFile.LOGGING_TAG, "payload length: " + payloadLength);
fileLength = (int) file.length();
Logger.d(AsyncEgnyteUploadFile.LOGGING_TAG, "bytes: " + fileLength);
connection.setFixedLengthStreamingMode(fileLength + payloadLength);
fileSize = fileLength;
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setRequestProperty("Authorization", "Bearer " + mToken);
// Enable POST method
connection.setRequestMethod(HttpPost.METHOD_NAME);
connection.setRequestProperty("Connection", "close");
// This header doesn't count to the number of bytes being sent.
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.connect();
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(payload[0]);
outputStream.writeBytes(payload[1]);
outputStream.writeBytes(payload[2]);
bufferSize = Math.min(fileLength, maxBufferSize);
buffer = new byte[bufferSize];
long totalBytesRead = 0;
long lastProgressTime = 0;
// Read file
bytesToRead = fileInputStream.read(buffer, 0, bufferSize);
boolean stopUploading = (FileState.UPLOADING != mFileInfo.getState() || isCancelled());
while (bytesToRead > 0 && !stopUploading)
{
outputStream.write(buffer);
totalBytesRead += bytesToRead;
Logger.d(AsyncEgnyteUploadFile.LOGGING_TAG, "bytes written: " + totalBytesRead);
final long now = System.currentTimeMillis();
bufferSize = (int) Math.min(fileLength - totalBytesRead, maxBufferSize);
buffer = new byte[bufferSize];
bytesToRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(payload[3]);
outputStream.writeBytes(payload[4]);
// Responses from the server (code and message)
final int serverResponseCode = connection.getResponseCode();
if (serverResponseCode == HttpStatus.SC_OK || serverResponseCode == HttpStatus.SC_CREATED) {
mAlreadyUploaded = true;
return JBError.JBERR_SUCCESS;
} else {
Log.e(AsyncEgnyteUploadFile.LOGGING_TAG, "error code: " + serverResponseCode);
return serverResponseCode;
}
} catch (final SocketTimeoutException e) {
..
} catch (final UnknownHostException e) {
..
} catch (final SocketException e) {
..
} catch (final IOException e) {
..
} catch (final Exception ex) {
..
} finally {
closeAll(connection, fileInputStream, outputStream);
}
}
Uploading a text file with only 12345 inside with this code results in following:
--*****
Content-Disposition: form-data; name="uploadedfile";filename="/storage/emulated/0/Download/3.txt"
12345
--*****--
What am I doing wrong?

You copy code is wrong. This is how to copy between streams in Java:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Notes:
You must check all reads for end of stream.
You must use the read count in the write() method.
You don't need a new buffer per read, and you don't need a buffer the size of the file. This will work with any buffer size greater than zero. I usually use 8192.

I suspect that your server is not designed / configured to handle "multi-part" uploads.
It certainly looks like it is treating this as a plain upload ... and I cannot see anything wring with the multi-part encapsulation.
(EJP is correct, but that is not what is causing your problem here. Your example shows that all of the characters were sent ...)

Related

I get always Server Response ok 200 even if I give the wrong password and files are not saved on server

I am uploading files to my server with a Java class in my Android APP.
I am using a simple php Skript to check a password.
If I give the wrong password, the file is not saved on the server and I should get 403, but I get OK 200 from the server.
Here is the Java Class
class httpUploadFile {
private int serverResponseCode = 0;
int uploadFile(String upLoadServerUri, String uploadFilePath, String uploadFileName,String pfad) {
String sourceFileUri=uploadFilePath + "" + uploadFileName;
HttpURLConnection conn;
DataOutputStream dos;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File not exist :"
+uploadFilePath + "" + uploadFileName);
return 0;
}
try {
FileInputStream fileInputStream = new FileInputStream(sourceFile);
String fulluri=getUrl(upLoadServerUri,pfad);
URL url = new URL(fulluri);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
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("uploaded_file", sourceFileUri);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ sourceFileUri + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
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();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
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();
Log.e("Upload file Exception", "Exception : "
+ e.getMessage(), e);
}
return serverResponseCode;
}
private String getUrl(String BASE_URL,String pfad) {
String token = getToken();
String key = getKey(token);
return String.format("%s?token=%s&key=%s&pfad=%s&", BASE_URL, token, key,pfad);
}
private String getKey(String token) {
return md5(String.format("%s+%s", "wrongpassword", token));
}
private String getToken() {
return md5(UUID.randomUUID().toString());
}
private static String md5(String s) {
MessageDigest m = null;
try {
m = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
assert m != null;
m.update(s.getBytes(), 0, s.length());
return new BigInteger(1, m.digest()).toString(16);
}
}
and here is the PHP
<?php
$shared_secret = "password";
$key = $_GET['key'];
$token = $_GET['token'];
$pfad = $_GET['pfad'];
if ($key != hash("md5", "{$shared_secret}+{$token}")) {
header('HTTP/1.0 403 Forbidden');
die('403 Forbidden: You are not allowed to access this file.');
}
$file_path = "/home/www/data/".$pfad."/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else {
echo "fail";
}
?>
HTTP 200 means transmission is OK on the HTTP level,that is to say, request was technically OK and server was able to respond properly.
200 doesn't judge whether your business logic is true or false, so even password is wrong, only if http communication between server and client is normal, 200 will be returned.
Generally we respond with HTTP 5xx if technical or unrecoverable problems happened on the server. Or HTTP 4xx if the incoming request had issues (e.g. wrong parameters)
Your backend server should do above judge.

Upload progress of files using HttpUrlConnection with multipart is super fast in android

I am trying to upload files using multipart with HttpUrlConnection POST method. The files are getting uploaded correctly and I am getting the response for that. But when I am tracking the progress, it just gives all the progress in 1 second even for files >100 MBs. It seems like the progress is for writing the file to buffer and not the network OutputStream. Calling flush() on the stream after writing each chunk of data doesn't help. Seems like flush just clears the stream to network and doesn't wait for the response before writing the next chunk.
Here's my code for uploading the file:
//Initialised in Constructor
boundary = twoHyphens + System.currentTimeMillis() + twoHyphens;
URL url = new URL(requestURL);
private HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
//This method is called to upload a file
public String uploadFile(String fieldName, File uploadFile) throws IOException, InterruptedException {
String fileName = uploadFile.getName();
FileInputStream fileInputStream = new FileInputStream(uploadFile);
DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(httpConn.getOutputStream()));
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
//returns no. of bytes present in fileInputStream
bytesAvailable = fileInputStream.available();
bufferSize = 4096;
buffer = new byte[4096];
long size = uploadFile.length();
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
int percentage = (int) ((bytesRead / (float) size) * 100);
dataOutputStream.write(buffer, 0, bufferSize);
dataOutputStream.flush(); //doesn't help
bytesAvailable = fileInputStream.available();
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}//This finishes in 1 second
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
int status = httpConn.getResponseCode();
StringBuilder sb = new StringBuilder();
BufferedReader reader = null;
try {
if (status == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} else {
throw new IOException("Server exception with status code: " + status);
}
} catch (Exception e) {
} finally {
if (reader != null) {
reader.close();
httpConn.disconnect();
}
}
return sb.toString();
}
Any help or explanation on this is really appreciated.
Writing to the output stream does not actually trigger the network connection. The data upload to the server is done when you call getResponseCode() , as I have detailed in my other ansswer
Only if you have some way to ask the getResponseCode() to report progress, otherwise you have no way to monitor the progress.

Pause/Resume Httpurl connection while uploading large files - Android

I was able to upload the large files (Tested upto 1.2GB) to server using .setChunkedstreamingmode() using httpurlconnection. I learnt that we have to keep the url-connection live to send the large sized files. The code i used to upload the large sized files is,
public static String uploadFileToServer(String filename, String targetUrl) {
String response = "error";
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String pathToOurFile = filename;
String urlServer = targetUrl;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(new File(
pathToOurFile));
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(1024);
// 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);
String token = "anyvalye";
outputStream.writeBytes("Content-Disposition: form-data; name=\"Token\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd);
outputStream.writeBytes("Content-Length: " + token.length() + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(token + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
String taskId = "anyvalue";
outputStream.writeBytes("Content-Disposition: form-data; name=\"TaskID\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd);
outputStream.writeBytes("Content-Length: " + taskId.length() + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(taskId + lineEnd);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
String connstr = null;
connstr = "Content-Disposition: form-data; name=\"UploadFile\";filename=\""
+ pathToOurFile + "\"" + lineEnd;
outputStream.writeBytes(connstr);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
System.out.println("Image length " + bytesAvailable + "");
try {
while (bytesRead > 0) {
try {
outputStream.write(buffer, 0, bufferSize);
} catch (OutOfMemoryError e) {
e.printStackTrace();
response = "outofmemoryerror";
return response;
}
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
} catch (Exception e) {
e.printStackTrace();
response = "error";
return response;
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
System.out.println("Server Response Code " + " " + serverResponseCode);
System.out.println("Server Response Message "+ serverResponseMessage);
if (serverResponseCode == 200) {
response = "true";
}else
{
response = "false";
}
fileInputStream.close();
outputStream.flush();
connection.getInputStream();
//for android InputStream is = connection.getInputStream();
java.io.InputStream is = connection.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while( ( ch = is.read() ) != -1 ){
b.append( (char)ch );
}
String responseString = b.toString();
System.out.println("response string is" + responseString); //Here is the actual output
outputStream.close();
outputStream = null;
} catch (Exception ex) {
// Exception handling
response = "error";
System.out.println("Send file Exception" + ex.getMessage() + "");
ex.printStackTrace();
}
return response;
}
Now during my upload process, if i pause the upload and resume, then it is starting from first byte instead of computing the chunks received by server. To overcome this problem, i coded as
// Initial download.
String lastModified = connection.getHeaderField("Last-Modified");
// Resume Upload.
connection.setRequestProperty("If-Range", lastModified);
But i am not able to resume the upload process. Can anyone please help me on this issue since i am newly learning this concepts. Thanks in Advance.
If the receiving server supports it, you can use the Content-Range header to identify a resuming upload. The Google-Drive API supports it. If you roll your own, I'd follow the pattern Google uses:
Begin upload and get a session identifier.
When upload is interrupted, wait until internet is available to resume.
When resuming upload, first inquire of the server how many bytes it has received. (*)
Resume upload with the next byte after the server's status.
(*) Note that when I rolled my own before, I added an encoded response from the server with the last KB of upload, just to verify it wasn't corrupted in transfer. However, I've never, in production, seen a case where a server had received corrupt data.

Uploading file to server NOT WORKING

My code is below.
After uploading (time is varying for different file sizes) I got 200 Ok and response
public class CloudFileUploader extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
int serverResponseCode = 0;
try {
FileInputStream fileInputStream = new FileInputStream(mFile);
URL url = new URL(CloudConstants.getFileUploadBaseUrl());
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary + ";key=fileToUpload");
conn.setRequestProperty("Accept", "application/json");
String contentLength=Long.toString(mFile.length());
// conn.setRequestProperty("Content-Length",contentLength );
AppSharedPreference mPref = new AppSharedPreference(mContext);
String token = mPref.getStringPrefValue(PreferenceConstants.USER_TOKEN);
conn.setRequestProperty("token", token);
conn.setRequestProperty("groupId", "" + mMessage.getReceiverId());
conn.setRequestProperty("message", "" + mMessage.getMessageBody());
conn.setRequestProperty("messageType", "" + mMessage.getMessageType());
conn.setRequestProperty("senderName", "" + mMessage.getSenderName());
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"myFile\";filename=\"" + mFile.getName() + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
Log.i(TAG, "Initial .available : " + bytesAvailable);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = conn.getResponseCode();
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException | FileNotFoundException | ProtocolException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (serverResponseCode == 200) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException ex) {
ex.printStackTrace();
if (onFileUploadListener != null) {
onFileUploadListener.onUploadFailed(mMessage, new AppError(ErrorHandler.ERROR_FROM_SERVER, ErrorHandler.ErrorMessage.ERROR_FROM_SERVER));
}
}
return sb.toString();
} else {
return "Could not upload";
}
}
}
I put conn.setRequestProperty("Content-Length",contentLength ); but it will throw java.net.ProtocolException.
I tested differnt code but the issue is still there.
Below given is my php server script.
$status['apiId'] = _GROUP_FILE_UPLOAD_API;
$user_id = $this->user['user_id'];
$target_dir = ROOTDIR_PATH . DS . "data" . DS . "GroupFileUploads" . DS;
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$fileUpload = NULL;
if ($this->headers->get('groupId')) {
$fileUpload['groupId'] = $groupId = $this->headers->get('groupId')->getFieldValue();
}
if ($this->headers->get('messageType')) {
$fileUpload['messageType'] = $messageType = $this->headers->get('messageType')->getFieldValue();
} if ($this->headers->get('message')) {
$fileUpload['message'] = $message = $this->headers->get('message')->getFieldValue();
}
if ($this->headers->get('senderName')) {
$fileUpload['senderName'] = $senderName = $this->headers->get('senderName')->getFieldValue();
}
The code is not working. It is not saving anything to the folder I given.
But It is working from Postman and AdvancedRestClient
When I put die() then i Got
Array( [myFile] => Array ( [name] => 1495018448FaceApp_1494992050886.jpg [type] => [tmp_name] => /tmp/phpH2kH47 [error] => 0 [size] => 917953 ))
The [type] => should be image/jpg but it is empty

Progress bar resets itself?

When I upload files over 5MB, the progress bar resets itself when it reaches 4% and start from 0 every 10 sec. But, for files under 5MB, the progress bar works fine and reaches 100%
Is this because of maxBufferSize? The server max post size is 512MB and every thing else is unlimited, so the problem must be from my code but I'm not sure where.
Here is my code
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
//update Dialog box progress
mProgressDialog.setProgress(progress[0]);
if ( nofti_appended )
{
//update Notification progress
mBuilder.setProgress(100, progress[0], false);
}
}
protected String doInBackground(String... urls) {
String upLoadServerUri = upApi.uploadUrl;
String fileName = this.file_path;
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
File sourceFile = new File(fileName);
int sentBytes = 0;
long fileSize = sourceFile.length();
try
{
FileInputStream fileInputStream = new FileInputStream(new File(fileName));
URL url = new URL(upLoadServerUri);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(1024);
// 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=\"file[]\";filename=\""+ fileName + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
Log.v("Size",bytesAvailable+"");
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
if(isCancelled()){
break;
}
sentBytes += bytesRead;
publishProgress((int)(sentBytes * 100 / fileSize));
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
if(isCancelled()){
return "faild";
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
Scanner s;
s = new Scanner(connection.getInputStream());
s.useDelimiter("\\Z");
final String response = s.next();
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
fileInputStream.close();
outputStream.flush();
outputStream.close();
if(serverResponseCode == 200)
{
return response;
}
} catch (MalformedURLException ex) {
} catch (final Exception e) {
}
return "faild";
}
Any ideas?
I think you actually have two problems with your progress calculation:
First, your logic is not quite right. It should be (see the next paragraph for the reason why):
(sentBytes / fileSize) * 100
The second problem, though, is that you're using int values, but trying to do a floating point calculation. (Percentage is 0.01 - 1.00, and then it's multiplied by 100 to turn it into 1% - 100%.) You need to do the calculation as floating point, and then cast the final value to integer.
Try something like
publishProgress((int)(((sentBytes * 1.0) / fileSize) * 100)));
That's getting to be a lot of () pairs, though. It would be better to declare a separate float or double variable, and use it instead:
percentDone = (sentBytes * 1.0) / fileSize * 100;
publishProgress((int)percentDone);

Categories

Resources