HTTPComponents multipart/form-data in Android - android

How to send file in POST-query using Apache HTTPComponents?

One possible solution is to generate HTTP headers by yourself, as explained here - http://en.wikipedia.org/wiki/MIME (see "Multipart messages")
I wrote such function. Maybe it is not well-written, but it works great.
private static final String REQUEST_BOUNDARY = "somethingUniqueForYourQuery";
private static String sendRequest(String url, String method, String params, File file, String fileField) {
HttpURLConnection httpConn = null;
StringBuilder httpContent = new StringBuilder();
String lineEnd = "\r\n";
String twoHyphens = "--";
byte[] fileContent = new byte[0];
int fileSize = 0;
// trying to read file
if (file != null) {
try {
FileInputStream fileInputStream = new FileInputStream(file);
httpContent.append(twoHyphens + REQUEST_BOUNDARY + lineEnd);
httpContent.append("Content-Disposition: form-data; name=\"" + fileField + "\"; filename=\"" + file.getName() + "\"" + lineEnd);
httpContent.append(lineEnd);
fileSize = fileInputStream.available();
fileContent = new byte[fileSize];
fileInputStream.read(fileContent, 0, fileSize);
fileInputStream.close();
}
catch (Exception e){
Log.d(DEBUG_TAG, "Exception occured: " + e.toString());
}
}
// trying to perform request
try {
httpConn = (HttpURLConnection) new URL(url).openConnection();
if (httpConn != null) {
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setUseCaches(false);
httpConn.setConnectTimeout(CONNECTION_TIMEOUT_STRING);
httpConn.setRequestMethod(method);
if (file != null && httpContent.length() > 0) {
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + REQUEST_BOUNDARY);
DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
if (params != null) {
dos.writeBytes(params);
}
dos.writeBytes(httpContent.toString());
dos.write(fileContent, 0, fileSize);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + REQUEST_BOUNDARY + twoHyphens + lineEnd);
dos.flush();
dos.close();
}
else if (params != null) {
PrintWriter out = new PrintWriter(httpConn.getOutputStream());
out.print(params);
out.close();
}
httpConn.connect();
int response = httpConn.getResponseCode();
BufferedReader rd;
if (httpConn.getErrorStream() == null) {
rd = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
} else {
rd = new BufferedReader(new InputStreamReader(httpConn.getErrorStream()));
}
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line + "\n");
}
if (rd != null) {
rd.close();
}
return sb.toString();
} else {
Log.d(DEBUG_TAG, "Connection Error");
}
}
catch (Exception e){
Log.d(DEBUG_TAG, "Exception occured: " + e.toString());
}
finally {
if (httpConn != null) {
httpConn.disconnect();
}
}
return null;
}

Related

Android Java file upload to Django backend

I have tried relentlessly to create a succesfull file upload from my JAVA/Android project to Django/Python backend.
The file I am trying to upload is a wav audio file which is stored on the phone.
I am trying to mix two sets of code.
The Android code I am using is the one taken from: How to upload a WAV file using URLConnection.
public class curlAudioToWatson extends AsyncTask<String, Void, String> {
String asrJsonString="";
#Override
protected String doInBackground(String... params) {
String result = "";
try {
Log.d("Msg","**** UPLOADING .WAV to ASR...");
URL obj = new URL(ASR_URL);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
//conn.setRequestProperty("X-Arg", "AccessKey=3fvfg985-2830-07ce-e998-4e74df");
conn.setRequestProperty("Content-Type", "audio/wav");
conn.setRequestProperty("enctype", "multipart/form-data");
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
String wavpath=mRcordFilePath;
File wavfile = new File(wavpath);
boolean success = true;
if (wavfile.exists()) {
Log.d("Msg","**** audio.wav DETECTED: "+wavfile);
}
else{
Log.d("Msg","**** audio.wav MISSING: " +wavfile);
}
String charset="UTF-8";
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
OutputStream output=null;
PrintWriter writer=null;
try {
output = conn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
byte [] music=new byte[(int) wavfile.length()];//size & length of the file
InputStream is = new FileInputStream (wavfile);
BufferedInputStream bis = new BufferedInputStream (is, 16000);
DataInputStream dis = new DataInputStream (bis); // Create a DataInputStream to read the audio data from the saved file
int i = 0;
copyStream(dis,output);
}
catch(Exception e){
}
conn.connect();
int responseCode = conn.getResponseCode();
Log.d("Msg","POST Response Code : " + responseCode + " , MSG: " + conn.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.d("Msg","***ASR RESULT: " + response.toString());
JSONArray jresponse=new JSONObject(response.toString()).getJSONObject("Recognition").getJSONArray("NBest");
asrJsonString=jresponse.toString();
for(int i = 0 ; i < jresponse.length(); i++){
JSONObject jsoni=jresponse.getJSONObject(i);
if(jsoni.has("ResultText")){
String asrResult=jsoni.getString("ResultText");
//ActionManager.getInstance().addDebugMessage("ASR Result: "+asrResult);
Log.d("Msg","*** Result Text: "+asrResult);
result = asrResult;
}
}
Log.d("Msg","***ASR RESULT: " + jresponse.toString());
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.d("Msg","POST FAILED: " + response.toString());
result = "";
}
} catch (Exception e) {
Log.d("Msg","HTTP Exception: " + e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(String result) {
if(!result.equals("")){
Log.d("Msg","onPostEXECUTE SUCCESS, consuming result");
//sendTextInputFromUser(result);
//ActionManager.getInstance().addDebugMessage("***ASR RESULT: "+asrJsonString);
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}else{
Log.d("Msg","onPostEXECUTE FAILED" );
}
}
}
public void copyStream( InputStream is, OutputStream os) {
final int buffer_size = 4096;
try {
byte[] bytes = new byte[buffer_size];
int k=-1;
double prog=0;
while ((k = is.read(bytes, 0, bytes.length)) > -1) {
if(k != -1) {
os.write(bytes, 0, k);
prog=prog+k;
double progress = ((long) prog)/1000;///size;
Log.d("Msg","UPLOADING: "+progress+" kB");
}
}
os.flush();
is.close();
os.close();
} catch (Exception ex) {
Log.d("Msg","File to Network Stream Copy error "+ex);
}
}
The Django backend code is taken from: https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html and I am using the simple upload:
def simple_upload(request):
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
return render(request, 'core/simple_upload.html', {
'uploaded_file_url': uploaded_file_url
})
return render(request, 'core/simple_upload.html')
I have already disabled the need for CSRF using #csrf_exempt.
I am getting the error "MultiValueDictKeyError" since Java does not post the file with the name 'myfile' for request.FILES['myfile'] to catch. Is have tried removing the ['myfile'] and just use request.FILES but then I get an error on
filename = fs.save(myfile.name, myfile)
saying there is no name to fetch.
Can I post the file so that it it catched by
request.FILES['myfile']
or is there better/simpler Django backend-code to use for communication with Android/IOS.
Thanks in advance and I apologize if this is a stupid question but I am dead stuck.
Here I go again answering my own question.
I found the following code from Android:How to upload .mp3 file to http server?
Using that instead of How to upload a WAV file using URLConnection and changing the line: dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
To dos.writeBytes("Content-Disposition: form-data; name=\"myfile\";filename=\"" + existingFileName + "\"" + lineEnd);
fixed my problem.

Android: Send file to server with parameters

I decided to rewrite my old code because HttpPost, HttpResponse and HttpEntity now are deprecated. Here is my old code:
private static String uploadFile(String token, File tempFile, String uploadUrl, final String fileName)
throws IOException, ExecutionException, InterruptedException {
try {
FileInputStream in = new FileInputStream(tempFile);
byte[] fileBytes = org.apache.commons.io.IOUtils.toByteArray(in);
in.close();
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("token", new StringBody(token, ContentType.TEXT_PLAIN));
builder.addPart("name", new StringBody(fileName, ContentType.TEXT_PLAIN));
builder.addPart("file", new ByteArrayBody(fileBytes, fileName));
builder.addPart("fileType", new StringBody("IMAGE", ContentType.TEXT_PLAIN));
HttpPost postRequest = new HttpPost(uploadUrl);
postRequest.setEntity(builder.build());
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
org.apache.http.HttpResponse response = httpClient.execute(postRequest);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
HttpEntity urlEntity = response.getEntity();
String str = org.apache.commons.io.IOUtils.toString(urlEntity.getContent());
JsonObject jsonObject = new JsonParser().parse(str).getAsJsonObject();
String Url = jsonObject.get("url").getAsString();
String blobKey = jsonObject.get("key").getAsString();
return Url;
}
}
}
So, now I'm looking for some alternative. I look to HttpURLConnection, but is there any way to add parameters to request?
I'll be glad for any help or hint
Fully worked code
public class FileUploader {
private static final String LINE_FEED = "\r\n";
private String boundary;
private HttpURLConnection httpConn;
private String charset = "UTF-8";
private OutputStream outputStream;
private PrintWriter writer;
public String worker(String url, String params) {
String requestURL = url;
try {
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
try {
JSONObject obj = new JSONObject(params);
Iterator<String> iter = obj.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = obj.get(key);
Logger.e("key " + key + " value " + value.toString());
multipart.addFormField("" + key, "" + value.toString());
} catch (JSONException e) {
// Something went wrong!
return null;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
/*
if u have file add this parametr
*/
// multipart.addFilePart("photo", file);
List<String> response = multipart.finish();
System.out.println("SERVER REPLIED:");
StringBuilder sb = new StringBuilder();
if (response == null) {
return null;
}
for (String line : response) {
System.out.println(line);
sb.append(line);
}
return sb.toString();
} catch (IOException ex) {
System.err.println(ex);
}
return null;
}
public class MultipartUtility {
public MultipartUtility(String requestURL, String ch)
throws IOException {
charset = ch;
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
//if need autorization
//httpConn.setRequestProperty("Authorization", "Basic " + encoded);
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
}
public void addFormField(String name, String 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();
}
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
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[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
int status = httpConn.getResponseCode();
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 {
BufferedReader r = new BufferedReader(new InputStreamReader(httpConn.getErrorStream()));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
Logger.e("Exception : " + total.toString());
return null;
}
return response;
}
}
}
and how to use :
FileUploader fileUploader = new FileUploader();
String result = fileUploader.worker(url, params)
params - its jsonobject converted to string ( mJsonObject.toString() )
// multipart.addFilePart("photo", file);
photo = param on server (popular its filename/file/photo/image)

Android HttpURLConnection image uploads but file not recognized as JPEG

I have this code which is able to upload a JPEG file to the server but the file is not recognized as JPEG. I think my problem is about encoding the JPEG file correctly. My solution is essentially the same as this one. I have tried other variants in appending the JPEG bytes using FileInputStream and using DataOutputStream instead of OutputStreamWriter, etc to no avail. Any suggestion appreciated.
final String boundary = "==================";
final String mimeType = "image/jpeg";
final int IMAGE_QUALITY = 100;
URL url = null;
HttpURLConnection urlConnection = null;
OutputStreamWriter request = null;
String response = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true); ///
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
urlConnection.setRequestMethod("POST");
OutputStream outputStream= urlConnection.getOutputStream();
request = new OutputStreamWriter(outputStream);
request.append("--" + boundary).append("\n");
request.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFileName + "\"").append("\n\n");
request.append("Content-Type: " + mimeType).append("\n\n");
request.append("Content-Encoding: base64").append("\n\n");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageThumbnail.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, stream);
byte[] byteArray = stream.toByteArray();
//request.append(new String(byteArray)).append("\n");
String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
request.append(encodedImage);
request.append("--" + boundary + "--");
request.flush();
request.close();
String line = null;
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
response = sb.toString(); // = "Success"
isr.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
response = "Malformed URL";
} catch (IOException e) {
e.printStackTrace();
response = "IO Exception";
}
return response;
Thanks to this post here, solution is as follows:
final String boundary = "==================";
final String twoHyphens = "--";
final String crlf = "\r\n";
final String mimeType = "image/jpeg";
final int IMAGE_QUALITY = 100;
URL url = null;
HttpURLConnection urlConnection = null;
DataOutputStream dos;
String response = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true); ///
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
//urlConnection.setRequestProperty("Content-Type", "image/jpeg");
urlConnection.setRequestMethod("POST");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageThumbnail.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, stream);
byte[] byteArray = stream.toByteArray();
dos = new DataOutputStream(urlConnection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + crlf);
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFileName + "\"" + crlf);
dos.writeBytes("Content-Type: " + mimeType + crlf);
dos.writeBytes(crlf);
dos.write(byteArray);
dos.writeBytes(crlf);
dos.writeBytes(twoHyphens + boundary + twoHyphens);
dos.flush();
dos.close();
String line = null;
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
response = sb.toString();
isr.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
response = "Malformed URL";
} catch (IOException e) {
e.printStackTrace();
response = "IO Exception";
}
return response;
I have these inside the #Override protected String doInBackground(String... params) of an AsyncTask<String, Void, String>

Unable to upload image to server in android

I have made a form activity in android which contains some textfields and photo,I want to send this parameters to server
I am able to uplaod all other parameters successfully,But image is not uploading to server,Please help me save me..Thank you,My code is as below:
code
Bitmap bitmap;
onClick(){
editEnable();
System.out.println("::::::::::save clicked:::::::::");
header.edit.setVisibility(View.GONE);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
// new EditProfileAPI().execute();
new ImageUploadTask().execute();
// Profile Edit Call...!!!
break;
}
class ImageUploadTask extends AsyncTask<Void, Void, String> {
private StringBuilder s;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(HomeActivity.this);
pDialog.setMessage("Loading");
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(Void... unsued) {
try {
String sResponse = "";
String url = Const.API_eDIT_PROFILE + "?";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("customer_id", new StringBody(Pref.getValue(HomeActivity.this, Const.PREF_CUSTOMER_ID, "")));
entity.addPart("first_name", new StringBody(et_firstname.getText().toString().trim()));
entity.addPart("last_name", new StringBody(et_lastname.getText().toString().trim()));
entity.addPart("customer_add", new StringBody(tv_adres.getText().toString().trim()));
entity.addPart("customer_phone", new StringBody(tv_phone.getText().toString().trim()));
entity.addPart("business_info", new StringBody(tv_busines.getText().toString().trim()));
entity.addPart("business_type", new StringBody(tv_busines_typ.getText().toString().trim()));
entity.addPart("bank_ac", new StringBody(tv_bank_acnt.getText().toString().trim()));
entity.addPart("dr_cr_card", new StringBody(tv_card.getText().toString().trim()));
entity.addPart("purpose_code", new StringBody(et_purpose_code.getText().toString().trim()));
entity.addPart("paypal_email", new StringBody(tv_paypal_email.getText().toString().trim()));
entity.addPart("password", new StringBody(et_fpassword.getText().toString().trim()));
entity.addPart("filename", new StringBody("test2.jpg"));
entity.addPart("files[]", new ByteArrayBody(data, "image/jpeg", "test2.jpg"));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return s.toString();
} else {
return "{\"status\":\"false\",\"message\":\"Some error occurred\"}";
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
System.out.println("::::::::::::::::::::::::::::MY exception in edit::::::::::::::::" + e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String sResponse) {
try {
pDialog.dismiss();
if (sResponse != null) {
Toast.makeText(getApplicationContext(), sResponse + " Photo uploaded successfully", Toast.LENGTH_SHORT).show();
System.out.println("::::::::::::::::::::::::::::MY SUCCESS RESPONESE in edit::::::::::::::::" + sResponse);
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
Upload image or media file
public void doFileUpload(String videoPath) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = videoPath;
String str = "";
System.out.println("(Talk)videoPath" + existingFileName);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 10 1024 1024;
try {
// ------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(
existingFileName));
// open a URL connection to the Servlet
URL url = new URL(url1);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
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=\""
+ existingFileName + "\"" + 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);
// close streams
Log.e("Debug", "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
// ------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
}
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}

Cannot upload a file using HttpUrlConnection

I am trying to upload a zip file to our server along with the params using UrlConnection. This is uploading the file but it is not sending the parameters.
Here is the code.
private static final String CRLF = "\r\n"; // Line separator required by multipart/form-data.
private static final String CHARSET_UTF_8 = "UTF-8";
private static final String TWO_HYPHENS = "--";
public static void uploadReport(String filePath) {
File binaryFile = new File(filePath);
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String urlString = "https://mycompany.com/api/file/uad.json";
HttpsURLConnection connection = null;
DataOutputStream dataOutoutStream = null;
try {
URL url = new URL(urlString);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
OutputStream output = connection.getOutputStream();
dataOutoutStream = new DataOutputStream(output);
// Send normal param.
writeParameter(dataOutoutStream, boundary, "app_name", "My App Name");
writeParameter(dataOutoutStream, boundary, "app_version", "2.04");
// Send binary file.
writeBinaryFile(output, dataOutoutStream, boundary, binaryFile);
// End of multipart/form-data.
dataOutoutStream.writeBytes("--" + boundary + "--" + CRLF);
Log.v(tag, "response code " + connection.getResponseCode());
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(UnsupportedEncodingException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} finally {
if (dataOutoutStream != null)
try {
dataOutoutStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is the code for my writeParameter method
private static void writeParameter(DataOutputStream dataOutputStream, String boundary, String paramName, String paramValue) throws IOException {
dataOutputStream.writeBytes(TWO_HYPHENS + boundary + CRLF);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + paramName + "\"" + CRLF);
dataOutputStream.writeBytes("Content-Type: text/plain; charset=" + CHARSET_UTF_8 + CRLF);
dataOutputStream.writeBytes(CRLF);
dataOutputStream.writeBytes(paramValue + CRLF);
dataOutputStream.flush();
}
Here is the writeBinaryFile method
private static void writeBinaryFile(OutputStream output, DataOutputStream dataOutputStream, String boundary, File binaryFile) throws IOException {
dataOutputStream.writeBytes(TWO_HYPHENS + boundary + CRLF);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"" + CRLF);
dataOutputStream.writeBytes("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()) + CRLF);
dataOutputStream.writeBytes("Content-Transfer-Encoding: binary" + CRLF);
dataOutputStream.writeBytes(CRLF);
dataOutputStream.flush();
InputStream input = null;
try {
input = new FileInputStream(binaryFile);
byte[] buffer = new byte[1024];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
// Important! Output cannot be closed. Close of writer will close output as well.
output.flush();
} finally {
if (input != null)
input.close();
}
dataOutputStream.writeBytes(CRLF);
dataOutputStream.flush();
}
May I know what I might be doing wrong.
I did check the Stackoverflow posts here and here.

Categories

Resources