Image not uploading to server while using GZIPOutputStream - android

I am able to upload image without using GZIPOutputStream to server. But i have requirement to use GZIPOutputStream. So i have used by :
public String multipartRequest(String urlTo, String post, String filepath, String filefield) throws ParseException, IOException {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
String result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String[] q = filepath.split("/");
int idx = q.length - 1;
try {
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
// code my
byte[] data = new byte[(int) file.length()];
URL url = new URL(urlTo);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
// connection.setRequestProperty("Content-Encoding", "gzip");
outputStream = new DataOutputStream(connection.getOutputStream());
// outputStream.writeBytes("HTTP/1.1 200 OK\r\n");
// outputStream.writeBytes("Content-Type: application/x-gzip");
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + ".gz" + "\""
+ lineEnd);
// outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" +
// q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
// buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(data, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(data, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(data, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
// Upload POST Data
String[] posts = post.split("&");
int max = posts.length;
for (int i = 0; i < max; i++) {
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
String[] kv = posts[i].split("=");
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + ".gz" + "\"" + lineEnd);
// outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(kv[1]);
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// For GZip outputStream //
try (GZIPOutputStream gzos = new GZIPOutputStream(outputStream)) {
gzos.write(data);
gzos.close();
Log.v("GZip", "Working");
} catch (IOException e) {
Log.v("TraceError", e.getMessage().toString());
e.printStackTrace();
}
// end
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
Log.v("MYRESULT", result);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
return result;
} catch (Exception e) {
Log.e("MultipartRequest", "Multipart Form Upload Error");
e.printStackTrace();
return "error";
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Here I am able to see
Log.v("GZip", "Working");
means file is compressed but image is not uploading to server.
I am not able to see this statement means not getting success. Also i m not getting any kind of error , warning etc nothing.
Log.v("MYRESULT", result);
So can anyone have a idea? Advanced help would be appreciated !

Finally i have solved with myself.!
I was doing mistake here !
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + ".gz" + "\"" + lineEnd);
I was appending ".gz" to other form data. I only needed to append file name.
Its really a silly !

You are not reading the inputstream correctly onto data. You are overwriting it on every loop. Change the code to
int totalBytesRead = 0;
bytesRead = fileInputStream.read(data, 0, data.length);
while (bytesRead > 0) {
totalBytesRead += bytesRead;
bytesRead = fileInputStream.read(data, totalBytesRead, data.length - totalBytesRead);
}
outputStream.write(data);

Related

How to send File and String data using HttpURLConnection in android

I am using HttpURLConnection to upload a file to the server but i could not figure out how can i add other parameters to send String data along with file.
This is the code i am using to upload the file.
public String sendFileToServer(String filename, String targetUrl) {
String response = "error";
Log.e("Image filename", filename);
Log.e("url", targetUrl);
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
// DataInputStream inputStream = null;
String pathToOurFile = filename;
String urlServer = targetUrl;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
DateFormat df = new SimpleDateFormat("yyyy_MM_dd_HH:mm:ss");
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 connstr = null;
connstr = "Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ pathToOurFile + "\"" + lineEnd;
Log.i("Connstr", connstr);
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);
Log.e("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();
Log.i("Server Response Code ", "" + serverResponseCode);
Log.i("Server Response Message", serverResponseMessage);
if (serverResponseCode == 200) {
response = "true";
}
String CDate = null;
Date serverTime = new Date(connection.getDate());
try {
CDate = df.format(serverTime);
} catch (Exception e) {
e.printStackTrace();
Log.e("Date Exception", e.getMessage() + " Parse Exception");
}
Log.i("Server Response Time", CDate + "");
filename = CDate
+ filename.substring(filename.lastIndexOf("."),
filename.length());
Log.i("File Name in Server : ", filename);
fileInputStream.close();
outputStream.flush();
outputStream.close();
outputStream = null;
} catch (Exception ex) {
// Exception handling
response = "error";
Log.e("Send file Exception", ex.getMessage() + "");
ex.printStackTrace();
}
return response;
}
I have used Volley previously but it fails to upload when file is large, I have to upload Video files up to 20 MB, so if you have any better solution please let me know.
I am using this code in Service so even if user close the app the uploading should continue.
The following code should work:
outputStream = new DataOutputStream(connection.getOutputStream());
// To send string data
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + stringName + "\""+lineEnd);
outputStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(stringValue + lineEnd);
outputStream.flush();
// To send file data
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
For more details: link

how to add token in httpurlconnection class

i am using this code for API access.But i have no idea how to add token as header in httpurlconnection class.my tag for token is "token".I want to add "token" tag with token value in header field but i have no idea.i have googled but i am confused
public JSONObject makeHttpRequest(String murl, Utils.method m, Map<String, String> parmas, String Token, String filepath, String filefield, String filemimetype){
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
String urlTo = SERVER_PATH + murl;
String result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
URL url = new URL(urlTo);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
// connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
if (Token != null){
connection.setRequestProperty("token", "Basic " + new String(Base64.encode(Token.getBytes(), 0)));
}
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
if (filepath != null) {
String[] q = filepath.split("/");
int idx = q.length - 1;
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + filemimetype + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
}
// outputStream.writeBytes(getQuery(parmas));
Iterator<String> keys = parmas.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = parmas.get(key);
System.out.println("Key :"+key+" and Value :"+value);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(value);
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
System.out.println("Response Code :"+connection.getResponseCode());
if (200 != connection.getResponseCode()) {
}
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
jobj = new JSONObject(result);
inputStream.close();
outputStream.flush();
outputStream.close();
connection.disconnect();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return jobj;
}

POST a file with other form data using HttpURLConnection

Im trying to POST a file to an API of mine along with other parameters.
Eg. POST /media
with the parameters
filename = 'test.png'
file = -the-actual-file-
I can do this successfully with Postman (using form-data), so the api side of things are fine.
Here is my android code using HttpURLConnection:
nameValuePairs.add(new BasicNameValuePair("filename", "test.png"));
URL object = new URL(url);
HttpURLConnection connection = (HttpURLConnection) object.openConnection();
connection.setReadTimeout(60 * 1000);
connection.setConnectTimeout(60 * 1000);
String auth = username+":"+password;
byte[] data = auth.getBytes();
String encodeAuth = "Basic " + Base64.encodeToString(data, Base64.DEFAULT);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Authorization", encodeAuth);
connection.setRequestProperty("Accept", ACCEPT);
connection.setRequestMethod("POST");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dataOutputStream = new DataOutputStream(connection.getOutputStream());
writer = new BufferedWriter(new OutputStreamWriter(dataOutputStream, "UTF-8"));
writer.write(getQuery(nameValuePairs));
writer.write("&file=" + "image.jpg");
writer.write
File file = getFile(item);
if (file == null) {
Log.e("uploadFile", "Source File not exist " );
} else {
addFilePart("file", file);
}
}
writer.flush();
writer.close();
dataOutputStream.close();
connection.connect();
Android multipart upload.
public String multipartRequest(String urlTo, Map<String, String> parmas, String filepath, String filefield, String fileMimeType) throws CustomException {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
String lineEnd = "\r\n";
String result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String[] q = filepath.split("/");
int idx = q.length - 1;
try {
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlTo);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
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=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + fileMimeType + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
// Upload POST Data
Iterator<String> keys = parmas.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = parmas.get(key);
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(value);
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
if (200 != connection.getResponseCode()) {
throw new CustomException("Failed to upload code:" + connection.getResponseCode() + " " + connection.getResponseMessage());
}
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
return result;
} catch (Exception e) {
logger.error(e);
throw new CustomException(e);
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Calling code:
//setup params
Map<String, String> params = new HashMap<String, String>(2);
params.put("foo", hash);
params.put("bar", caption);
String result = multipartRequest(URL_UPLOAD_VIDEO, params, pathToVideoFile, "video", "video/mp4");
//next parse result string
Ref Link https://stackoverflow.com/a/26145565/1143026
Accepted answer needs a small update if you are using nanoHttpd for server end., as this issue took a lot of debugging time.. and had to use the below timeline source code from insomnia to understand the problem.
just avoid using (//comment out) outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
as this ends up setting the post parameters to null

Upload file using HttpURLConnection

I've copied the following code from here, the one thing that I have replaced is using Map instead of the split as shown in commented lines below, my code start right after it.
This code works perfectly all the time except with one device where it fails sometimes, the code seems to be stuck inside this block, I didn't get any exception btw, it just stuck there.
while (iter.hasNext()) {
....
}
Update
I don't have physical access to the phone so I printed a log for each line, even the exception, and I see that the code is stuck in the loop mentioned above, and also note that the http parameters are fixed to 4.
I put a Log inside it and I see that it reached that block and finished all the params and then didn't get out of it, what am I doing here?
public ResponseObject multipartRequest(String urlTo, String post, Map httpPara, String filepath, String filefield) throws ParseException, IOException {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
int ResponseCode;
String twoHyphens = "--";
String boundary = "*****"+Long.toString(System.currentTimeMillis())+"*****";
String lineEnd = "\r\n";
String result = "";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String[] q = filepath.split("/");
int idx = q.length - 1;
try {
File file = new File(filepath);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlTo);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
Log.i(Commons.TAG, "filepath " + getMimeType(filepath) );
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] +"\"" + lineEnd);
// outputStream.writeBytes("Content-Type: video/mp4" + lineEnd);
outputStream.writeBytes("Content-Type: " + getMimeType(filepath) + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while(bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
// Upload POST Data
// String[] posts = post.split("&");
// int max = posts.length;
// for(int i=0; i<max;i++) {
// outputStream.writeBytes(twoHyphens + boundary + lineEnd);
// String[] kv = posts[i].split("=");
// outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd);
// outputStream.writeBytes("Content-Type: text/plain"+lineEnd);
// outputStream.writeBytes(lineEnd);
// outputStream.writeBytes(kv[1]);
// outputStream.writeBytes(lineEnd);
// }
//
Iterator iter = httpPara.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry para = (Map.Entry) iter.next();
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + para.getKey().toString() + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain"+lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(para.getValue().toString());
outputStream.writeBytes(lineEnd);
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
outputStream.flush();
outputStream.close();
ResponseCode = connection.getResponseCode();
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
fileInputStream.close();
inputStream.close();
return new ResponseObject(ResponseCode, result);
} catch(Exception e) {
Log.e("MultipartRequest","Multipart Form Upload Error");
e.printStackTrace();
return null;
}
}

How to Upload large files using ChunkedStreaming in android?

I need to post some large files to server. I am able to upload the files which are < 3 MB , but while i am uploading a file which is > 3 MB, it shows me the Internal server exception and server response code "500". Initially, I thought it is a server side issue but I can post the large file through iOS app(By using the same url), same way I need to implement it in android.
Here is my code --
public String postMediaDataToServer(String evidenceId, File file) {
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "----WebKitFormBoundarysNDKBMUFqqvzYWGh";
Date date = new Date();
String timestamp = dateFormat.format(date);
String fileName = file.getName();
if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
fileName = "image_" + timestamp + ".jpg";
} else if (fileName.endsWith(".wav")) {
fileName = "audio_" + timestamp + ".wav";
} else if (fileName.endsWith(".mp4")) {
fileName = "video_" + timestamp + ".mp4";
} else if (fileName.endsWith(".3gp")) {
fileName = "video_" + timestamp + ".3gp";
}
String response = "error";
Log.e("Image filename", fileName);
Log.e("url", ApplicationData.getBaseUrl()
+ "Media");
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
// DataInputStream inputStream = null;
String pathToOurFile = fileName;
String urlServer = ApplicationData.getBaseUrl()
+ "Media";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024;
try {
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(1000*1024);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("X-Ecordia-Software", "ecordiApp");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="
+ boundary);
List<Cookie> cookies = ApplicationData.getCookieStore()
.getCookies();
if (cookies.size() > 0)
connection.setRequestProperty("Cookie", cookies.get(0).getName() + "="
+ cookies.get(0).getValue());
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"EvidenceIdentifier\""
+ lineEnd + lineEnd);
outputStream.writeBytes(evidenceId + lineEnd);
outputStream.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
outputStream.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd + lineEnd);
} else if (fileName.endsWith(".mp4")) {
outputStream.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: video/mp4" + lineEnd + lineEnd);
} else if (fileName.endsWith(".wav")) {
outputStream.writeBytes("Content-Disposition: form-data; name=\"File0\"; filename=\""
+ fileName + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: audio/wav" + lineEnd + lineEnd);
}
outputStream.writeBytes(lineEnd + twoHyphens + boundary + twoHyphens
+ lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.e("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();
Log.i("Server Response Code ", "" + serverResponseCode);
Log.i("Server Response Message", serverResponseMessage);
if (serverResponseCode == 200) {
response = "true";
}
fileInputStream.close();
outputStream.flush();
outputStream.close();
outputStream = null;
} catch (Exception ex) {
// Exception handling
response = "error";
Log.e("Send file Exception", ex.getMessage() + "");
ex.printStackTrace();
}
return response;
How to solve this issue?

Categories

Resources