Uploading image multi part form from android - android

i have this problem that i want to upload image on a server through multi-part form but its keep giving me invalid image when i try to upload it from android but work fine from web.
this is html form which work fine.
http://letitripple.org/htmlForm.html
this is the request this html form create. (i get from chrome developer tool)
------WebKitFormBoundaryPug6xAUAlaUPbR86
Content-Disposition: form-data; name="wp-user-avatars"; filename="Desert.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryPug6xAUAlaUPbR86
Content-Disposition: form-data; name="login_id"
51
------WebKitFormBoundaryPug6xAUAlaUPbR86
Content-Disposition: form-data; name="cookie"
ali.asim#gmail.com|1473394633|vcN3CTbKi6pkAjPMKH1D9MHucPLKhw3wyeS7ViSTgGb|f5cbd913f6c3d6940066a660bac5908adb016682ce34f48e8200773eb4503c1e
------WebKitFormBoundaryPug6xAUAlaUPbR86
Content-Disposition: form-data; name="submit"
submit
------WebKitFormBoundaryPug6xAUAlaUPbR86--
This is my android code which is not working.
public AppResponse uploadImageFile(String csURL, String csFilePath)
{
AppResponse appResponse = null;
HttpURLConnection conn = null;
DataOutputStream dos = null;
ByteArrayOutputStream output = null;
InputStream inStream = null;
String Url = csURL;
String existingFileName = csFilePath;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "WebKitFormBoundaryleA9RIQsQBxW8Cgl";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
// String reponse_data = null;
int maxBufferSize = 1 * 1024 * 1024;
// String urlString = "YOUR PHP LINK FOR UPLOADING IMAGE";
try {
//------------------ CLIENT REQUEST
// FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
// open a URL connection to the Servlet
URL url = new URL(Url);
// 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);
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName));//You can get an inputStream using any IO API
byte[] bytes;
byte[] buffers = new byte[605244];
int bytesReads;
output = new ByteArrayOutputStream();
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + twoHyphens + twoHyphens + boundary);
//conn.setRequestProperty("attach1", existingFileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + twoHyphens + twoHyphens + boundary + "\r\n");
dos.writeBytes("Content-Disposition: form-data; name=\"attach1\"; filename=\"profile.jpg\"\n Content-Type: image/jpg\r\n\r\n\r\n"); // uploaded_file_name is the Name of the File to be uploaded
// 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);
Log.e("Value", "Writing");
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + twoHyphens + twoHyphens + boundary + twoHyphens);
//String strInput = dos.toString();
int responseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
fileInputStream.close();
dos.flush();
dos.close();
int nResponseCode = conn.getResponseCode();
inStream = new DataInputStream(conn.getInputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(inStream));
String line = "";
StringBuilder csResult = new StringBuilder("");
while ((line = in.readLine()) != null) {
Log.e("Debug", "Server Response " + csResult);
csResult.append(line);
}
appResponse = new AppResponse(nResponseCode, csResult.toString());
}
catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
return appResponse;
}

Related

Sending file with httpurlconnection the server response is badrequest (400)?

I have a code that worked for me to send files to the server, I have used it in a sales app, but I want to use it in another app and it does not work for me.
String sourceFileUri = root.toString()+"/"+filename;
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;
File sourceFile = new File(sourceFileUri);
//File sourceFile = root;
if (sourceFile.isFile()) {
try {
String upLoadServerUri =
"http://www.tucuenca.com/cspm/cargar_archivo.php";
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
//conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
//conn.setConnectTimeout (5000) ;
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE",
"multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("bill", sourceFileUri);
conn.setRequestMethod("POST");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data;
name=\"bill\";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();
if (serverResponseCode == 200) {
Log.i(TAG, "enviarArchivo: Cargar completa");
BufferedReader in=new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuffer sb= new StringBuffer("");
String line="";
while((line=in.readLine())!=null){
sb.append(line);
break;
}
resul=sb.toString();
in.close();
// showSuccessMessage("El servidor responde "+resul);
}else if(serverResponseCode==400){
Log.i(TAG, "enviarArchivo: error 400 "+resul);
// showSuccessMessage("Error en el servidor");
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
The server answers me with code 400, bad request, the url is active and working (http://www.tucuenca.com/cspm/cargar_archivo.php), I'm doing the tests in a huawei with android 9.
I await your comments.

Add param and video(file) in multiple request by post method in Andriod

I am uploading video from android app.i am able to add only video with this code,but i am giving request with video file,but its not working.i added code with this question,help me out from this.
public int uploadFile(final String sourceFileUri) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String action ="action=videoUpload&id="+pHelper.getuser_id()+"&project_id="+Constants.proj_id+"&site_id="+count_et;
Log.d("bf_encoding",action);
// encode
byte[] data = new byte[0];
try {
data = action.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String value = Base64.encodeToString(data, Base64.DEFAULT);
String twoHyphens = "--";
String boundary = "*****";
String mm = "gokgo8gg4ko4gco4okg4ws4o04k44w0go4k";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
return 0;
} else {
try {
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL("https://rahumanmusic.co.in/ar_site/api/video");
Log.d("WebService", "url=" + url);
// Open a HTTP connection to the URL
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("Headers","X-API-KEY=gokgo8gwskkog4ko4gco4okgo04k44w0go4k");
// conn.getHeaderFieldDate("X-API-KEY", Long.parseLong(mm));
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
Log.d("valuevalue",value);
conn.setRequestProperty("video_upload", filepathUrl1.getName());
conn.setRequestProperty("value", value);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"video_upload\";filename=\"" + filepathUrl1.getName() + "\"" + 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 (result)
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
result += line;
}
}
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.d("ssk", "result" + result);
return serverResponseCode;
} // End else block
}
In above code,converted base 64 string as value not passing in request. i am stuck in this task,help me out guys
Use this
library for multipart requests, i-e image, video or any other data for POST request

Android REST API client that allows file attachments for a http POST

Is anybody aware of an Android app that acts as a REST API client and allows attaching files? I'm looking to do the equivalent of this in Postman, but from an Android device:
I've tried "REST Client for Android" and "HTTP Client" available on Google Play, but these only seem to allow text in the body, not file attachments. Can anybody advise on options for this for Android currently ??
https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server
pls find above link for retrofit api mostly used restapi.
Use HttpURLConnection class to upload image on server.
String urlStr= "url link";
String response;
boolean isGetMethod = false;
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DataOutputStream dataOutputStream;
String lineEnd = "\r\n", twoHyphens = "--", boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
File file;
int maxBufferSize = 1024 * 1024;
FileInputStream fileInputStream;
try {
URL url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
if (!isGetMethod) {
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
file = new File("image file path");
fileInputStream = new FileInputStream(file);
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\"" + lineEnd);
dataOutputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
dataOutputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.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...
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dataOutputStream.flush();
dataOutputStream.close();
}
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuilder builder = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null) {
builder.append(inputLine);
}
response = builder.toString();
bufferedReader.close();
} else
return response;
} catch (Exception e) {
e.printStackTrace();
}
httpURLConnection.disconnect();
return response;
}
#Override
protected void onPostExecute(String response) {
}
}

how to send file from sd card to http post?

i want to send file from our app to sever through http post method.
My code is looking like as fallows
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/TamTrack/TamTrackDetails.xml";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://192.158.1.7/Geo/myfilename";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// 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)
Log.v("info",".size."+bytesRead);
for(int n1=0;n1<bytesRead;n1++)
{
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);
// close streams
Log.v("info","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.v("info", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.v("info", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.v("info","Server Response "+str);
}
inStream.close();
}
catch (IOException ioex)
{
Log.v("info", "error: " + ioex.getMessage(), ioex);
}
return null;
It is working fine.but empty file is created in server.
If any one know the solution ,please help me .
Thanks in advance.
Try this code. It is using a class "SimpleMultipartEntity" using which you can easily send the file.
I'd prefer using Apache Http commons, it is part of android. I think this is a much simpler and cleaner approach. You need to do something like this:
AndroidHttpClient client = AndroidHttpClient.newInstance("useragent string");
URI uri = "something";
File file = new File("/tmp/data");
HttpPost post = new HttpPost(uri);
post.setEntity(new FileEntity(file, "text/html"));
HttpResponse httpResponse = client.execute(post);
int statusCode = httpResponse.getStatusLine().getStatusCode();

Android emulator file read permission

I need to upload a file from my android emulator directory ('data\data\org.mypackage\file.dat') to a remote server, but when I try to access the file it gives an error like 'error: Permission denied', I store my sqlite database in 'data\data\org.mypackage\databases\' folder , during the application startup if there is no sqlite db in that folder I copied it from my asset folder to that directory and access it from there it works perfect but in the case upload task it ask for permission why this occur? following is my uploadFile method
private void uploadFile(){
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName="/data/data/org.mypackage/file.dat";
GeneralFunctions.comment(existingFileName);
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://117.231.150.213:8080/upload.jsp";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// 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
GF.showToast("File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (Exception ex)
{
GeneralFunctions.exception("error: " + ex.getMessage());
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
GeneralFunctions.comment("Server Response "+str);
}
inStream.close();
}
catch (Exception ioex){
GeneralFunctions.exception("error: " + ioex.getMessage());
}
}
Add INTERNET permission to your manifest.
If you can provide logcat then it will help more.

Categories

Resources