I am trying to upload a file to a server via HTTP POST from my device. I have two method upload1 and upload2.
Upload1 uses the HttpPost class and it works, but with bigger files it throws out of memory exception.
Upload2 uses HttpURLConnection and it does not work. (I get BAD REQUEST message from the server.) I want upload2 to work, because it uses stream to send the data and throws no out of memory exception.
I looked at the packages in wireshark, the headers are seems to be the same, however the length with upload1 is 380, with upload2 is only 94. What could be the problem?
private void upload1(File file) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url + "?recname="
+ fileName);
// ///////////////////////////////////////
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "---------------------------This is the boundary";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
FileInputStream fin = new FileInputStream(file);
byte audioData[] = new byte[(int) file.length()];
fin.read(audioData);
fin.close();
// Send a binary file
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Type: audio/mp4" + lineEnd);
dos.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
dos.writeBytes(lineEnd);
dos.write(audioData);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
dos.close();
ByteArrayInputStream content = new ByteArrayInputStream(
baos.toByteArray());
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(content);
entity.setContentLength(baos.toByteArray().length);
httppost.addHeader("Content-Type", "multipart/form-data; boundary="
+ boundary);
httppost.setEntity(entity);
// //////////////////////////////////
HttpResponse response = httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
reader.close();
message = builder.toString();
System.out.println(message);
} catch (UnknownHostException e) {
message = "Error! Server is unreachable. Check you internet connection!";
} catch (Exception e) {
message = "error: " + e.toString();
}
}
/////////////////////////////////////////////////////////////////////////////////////////
private void upload2(File file) {
HttpURLConnection connection = null;
String pathToOurFile = file.getPath();
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "---------------------------This is the boundary";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
fileInputStream = new FileInputStream(new File(pathToOurFile));
URL server_url = new URL(url+ "?recname="
+ fileName);
connection = (HttpURLConnection) server_url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
String bodyHeader = twoHyphens
+ boundary
+ lineEnd
+ "Content-Disposition: form-data; name=\"file\";filename=\""
+ fileName + "\"" + lineEnd + "Content-Type: audio/mp4"
+ lineEnd + "Content-Transfer-Encoding: binary" + lineEnd
+ lineEnd + twoHyphens + boundary + twoHyphens ;
byte[] bodyHeaderAray = bodyHeader.getBytes();
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("Expect", "100-continue");
// Content-Length
int bodyHeaderSize = (int) file.length() + bodyHeaderAray.length;
System.out.println("body header size: " + bodyHeaderSize);
// connection.setFixedLengthStreamingMode(bodyHeaderSize);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ fileName + "\"");
outputStream.writeBytes(lineEnd);
outputStream.writeBytes("Content-Type: audio/mp4" + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary"
+ lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
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(twoHyphens + boundary + twoHyphens
+ lineEnd);
fileInputStream.close();
outputStream.flush();
outputStream.close();
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
message = serverResponseMessage;
} catch (Exception ex) {
System.out.println(ex);
}
}
According to the Problems you are getting to upload the files. you should use Multipart mechanism to upload the files to server.
httpclient-4.1.jar
httpcore-4.1.jar
httpmime-4.1.jar
apache-mime4j-0.6.1.jar
For that you need to add couple of libraries into your project and use it for HTTP connection and file data.
private boolean uploadFile(File mFile) {
boolean success = true;
String filename = mFile.getName();
MultipartEntity data_to_send = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
try {
data_to_send.addPart(
"name",
new StringBody(
filename.substring(filename.lastIndexOf("/") + 1)));
data_to_send.addPart("fileData", new FileBody(mFile));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
String responseData = ConsumeWebService.sendRequest(data_to_send,
Global.BASE_URL + serviceUrl);
if (TextUtils.isEmpty(responseData)
|| responseData.equals(ConsumeWebService.ERROR_CODE)) {
success = false;
}
} catch (Exception e) {
success = false;
e.printStackTrace();
}
return success;
}
public static String sendRequest(MultipartEntity data, String url) {
String response = "";
response = postData(url, data);
return response;
}
private static String postData(String url, MultipartEntity data) {
String strResponse = "";
try {
Log.d(Global.TAG, "Post URL is " + url);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(data);
strResponse = httpClient.execute(httpPost,
new BasicResponseHandler());
} catch (UnsupportedEncodingException e) {
strResponse = ERROR_CODE;
e.printStackTrace();
} catch (ClientProtocolException e) {
strResponse = ERROR_CODE;
e.printStackTrace();
} catch (IOException e) {
strResponse = ERROR_CODE;
e.printStackTrace();
}
return strResponse;
}
You can build by your own your POST Request by following this w3.org docs about forms.
I think in upload2 you are missing one lineEnd where you do:
....
outputStream.writeBytes("Content-Transfer-Encoding: binary"
+ lineEnd);
After this, you have to transmit the data and it takes two lineEnds before actual data, so it should be:
....
outputStream.writeBytes("Content-Transfer-Encoding: binary"
+ lineEnd + lineEnd);
For reading files and place them in multipart/form-data structure, I suggest you this way that works for me:
FileInputStream fileInputStream=new FileInputStream(file);
byte[] bytes= new bytes[fileInputStream.getChannel().size()];
fileInputStream.read(bytes);
fileInputStream.close();
outputStream.write(bytes);
outputStream.writeBytes(lineEnd);
Hope it helps.
Related
I'm Working on used goods sell Android application where I want to upload multiple images of goods on server.User can upload maximum 4 images of and at least he has to upload one image of goods.The number of goods images may vary between 1 to 4,it depends on user what number of images he wants to upload.
Now my question is that how can I upload multiple images with String data to server in a single multipart request
Condition
the number of images upload is vary between 1 to 4 images.
Below is my codes for uploading single image to server with string data.
try {
if (selectedImage.equals(null)) {
Toast.makeText(MainActivity.this, "Choose Image First", Toast.LENGTH_LONG).show();
} else {
tvLoad.setVisibility(View.VISIBLE);
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", "34242");
params.put("user_city", "Delhi");
params.put("category", "vehicle");
params.put("subcategory", "car");
params.put("brand", "honda");
params.put("model", "2019");
params.put("fuel", "petrol");
params.put("conditn", "good");
params.put("title", "title");
params.put("description", "description");
params.put("year", "2018");
params.put("kmdriven", "90000");
params.put("price", "100000");
Log.e("abc", " =============" + link);
try {
multipartRequest(link, params, selectedImage + "", "image", "image/jpg");
} catch (Exception e) {
e.printStackTrace();
}
}
}catch (Exception e){
e.printStackTrace();
Toast.makeText(MainActivity.this, "Choose Image First", Toast.LENGTH_LONG).show();
}
public void multipartRequest(String urlTo, Map<String, String>
parmas, String filepath, String filefield, String fileMimeType) throws
Exception {
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 Exception("Failed to upload code:" + connection.getResponseCode() + " " + connection.getResponseMessage());
}
inputStream = connection.getInputStream();
result = this.convertStreamToString(inputStream);
fileInputStream.close();
inputStream.close();
outputStream.flush();
outputStream.close();
JSONObject jsonObject = new JSONObject(result);
if(jsonObject.getString("success").equals("true")){
Toast.makeText(MainActivity.this, "Service Added", Toast.LENGTH_LONG).show();
}else{
}
tvLoad.setText("Successfully loaded");
Log.e("abc", " ========= result === " + result) ;
try {
JSONObject jsonObject1 = new JSONObject(result);
String link = jsonObject1.getString("link");
tvLink.setText(link);
}catch (Exception e){
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
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();
}
I recommend my lightweight library with I have described in this answer https://stackoverflow.com/a/53253933/8849079
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
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);
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
I'm newbie in android and having problem uploading image in android. I'd already tried to find examples but got no luck:
I am having error saying:
and here is my code:
I have Array named "images" which contains the paths of images that I want to upload
e.g. /storage/sdcard0/DCIM/Camera/IMG_20131214_171438.jpg
//ONCLICK LISTENER
public OnClickListener upload_image = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(images.size() != 0) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
for(int i=0; i<images.size(); i++){
doFileUpload(images.get(i));
}
}
}
};
//UPLOAD
private void doFileUpload(String upload_file){
Log.d("Currently queued", upload_file);
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String exsistingFileName = upload_file;
// Is this the place are you doing something wrong.
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "acebdf13572468";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String urlString = "http://test.xponlm.com/MobileServices/api/ShipmentImages";
try
{
Log.e("MediaPlayer","Inside second Method");
FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );
URL url = new URL(urlString);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"ID\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(strshipmentID + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"ImageType\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes("JPG" + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"FileType\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(strtype + lineEnd);
Log.e("MediaPlayer","Headers are written");
bytesAvailable = fileInputStream.available();
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);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
// tv.append(inputLine);
Log.d("inputLine", inputLine);
// close streams
Log.e("MediaPlayer","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("MediaPlayer", "error1: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("MediaPlayer", "error2: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null) {
Log.e("MediaPlayer","Server Response"+str);
}
/*while((str = inStream.readLine()) !=null ){
}*/
inStream.close();
}
catch (IOException ioex){
Log.e("MediaPlayer", "error3: " + ioex.getMessage(), ioex);
}
}
Did I missed somthing? Can you tell what is the problem on my code?
public Fileupload(String url, String userid,
String filepath, String status) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
HttpParams httpParams = httpclient.getParams();
httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 100000);
try {
entity.addPart("key 1",
new StringBody(userid, Charset.forName("UTF-8")));
entity.addPart("key 2",
new StringBody(status, Charset.forName("UTF-8")));
entity.addPart("File ", new FileBody(new File(filepath)));
httppost.setEntity(entity);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
} catch (Exception e) {
}
}