Uploading imageFile to server android - android

Iam trying to upload image files to server. First i locally store the image path in the database and then create a new file using the path and try to upload the images using http post request. It is working fine for only 2 to 3 image file and if i try to upload continuously more than 3 image files one after the other the files are not uploaded. I have a very basic idea in networking.Plz kindly give me a solution.

You have to work like this
public void connectForMultipart() throws Exception {
con = (HttpURLConnection) ( new URL(url)).openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
con.connect();
os = con.getOutputStream();
}
public void addFormPart(String paramName, String value) throws Exception {
writeParamData(paramName, value);
}
public void addFilePart(String paramName, String fileName, byte[] data) throws Exception {
os.write( (delimiter + boundary + "\r\n").getBytes());
os.write( ("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + fileName + "\"\r\n" ).getBytes());
os.write( ("Content-Type: application/octet-stream\r\n" ).getBytes());
os.write( ("Content-Transfer-Encoding: binary\r\n" ).getBytes());
os.write("\r\n".getBytes());
os.write(data);
os.write("\r\n".getBytes());
}
public void finishMultipart() throws Exception {
os.write( (delimiter + boundary + delimiter + "\r\n").getBytes());
}
for getting response
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In place of image you can send anything(in your case its image file), you would like to... if it creates some heck then
you should divide the large file into small parts then try to sending.And Join this small part on the server.
In my case httpmime-4.2.1-1.jar is only needed in this code

refer this
Image Upload and Retrieve Android with WebServices (PHP Code)
The Repository contain 2 Android project .. Image Upload to Mysql and Image Retreival from Mysql
one folder contain webservices and mysql database
for Image Upload ... you only need insert.php
Let me if it wasn't worked

ByteArrayOutputStream stream = new ByteArrayOutputStream();
//follwing line compress Bitmap image
image.compress(Bitmap.CompressFormat.JPEG, 90, stream);
byte[] byteArray = stream.toByteArray();
String s= Base64.encodeToString(byteArray, Base64.DEFAULT);
here you will get a base64 encoded image, just send String s to server. you can decode image from server.

Use this one it will help you.
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
//FileBody bin = null;
MultipartEntity reqEntity = new MultipartEntity();
Bitmap rotatedBitmap2;
if(rotatedBitmap2 != null){
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
rotatedBitmap2.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data,"dcc/"+n+".jpg");
reqEntity.addPart("Image", bab);
}
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
//do some work
}
} catch (Exception ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}

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.

Bitmap does not draw after being sent from Android to Server

I have been hitting my head against a wall on this one.
In my Android App, I select an image. That all seems to be working fine. I then convert it to a byte array and HTTP POST it to a server. The data written to file on the server side does not appear to be what the data started as.
When checking things end-to-end it seems that the file on my device is 1,066,896 bytes. The data on the server is 14,745,600 bytes.
Code from Selecting the Image:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_IMAGE: {
if (resultCode != RESULT_OK)
return;
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
MainActivityFragment fragment = (MainActivityFragment)Fragments.Get("Main");
new SendPic().execute(bitmap);
} catch (IOException exception) {
Log.e(TAG, "Could not load image", exception);
}
break;
}
}
}
If I check bitmap.getByteCount() in the above code, it will report 14,745,600, which makes me relatively confident that the data being sent to the server is good. But I can't figure out while the data read in is 14x larger than what I show on the device. It I take this same bitmap though, and apply it to an ImageView, the image looks just fine.
SendPic is a simple class that extends AsyncTask. No magic there.
public static String SendHttpImage(String path, Bitmap bitmap, String name, String filename) {
String attachmentName = "bitmap";
String attachmentFileName = "bitmap.bmp";
String crlf = "\r\n";
String twoHyphens = "--";
String boundary = "******";
try {
String url = "http://server.com/index.php?" + path;
URL u = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection)u.openConnection();
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Cache-Control", "no-cache");
urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream request = new DataOutputStream(urlConnection.getOutputStream());
request.writeBytes(twoHyphens + boundary + crlf);
request.writeBytes("Content-Disposition: form-data; name=\"" + attachmentName + "\";filename=\"" + attachmentFileName + "\"" + crlf);
request.writeBytes(crlf);
int bytes = bitmap.getByteCount();
ByteBuffer buffer = ByteBuffer.allocate(bytes);
bitmap.copyPixelsToBuffer(buffer);
byte[] pixels = buffer.array();
request.write(pixels);
request.writeBytes(crlf);
request.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
request.flush();
request.close();
InputStream responseStream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();
String response = stringBuilder.toString();
urlConnection.disconnect();
return response;
} catch (IOException exception) {
Log.e (TAG, "HTTP Post failed", exception);
return null;
}
}
Thank you for your help with this!
Many thanks to #Colin Gillespie. I compressed the data to jpeg before sending to the server, and it came out perfect on the other side. I'm still quite confused as to why my browser couldn't display the raw bitmap, but I won't look a gift-horse in the mouth.

Send JSON and image with HttpURLConnection in android

i'm trying to send some data to a server. The server is waiting a json and an image. I tried with every example that i found but i couldn't send the data. Actually i'm sending the json params with a PrintWriter object, but it doesn't accept the image. I need to use HttpURLConnection not with the apache library. This is my piece of code working:
HttpURLConnection connection = null;
PrintWriter output = null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
attachImage.compress(Bitmap.CompressFormat.PNG, 40, stream);
byte[] imageData = stream.toByteArray();
String imagebase64 = Base64.encodeToString(imageData, Base64.DEFAULT);
Log.d(tag, "POST to " + url);
try{
URL url = new URL(this.url);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty(HTTP_CONTENT_TYPE, "application/json; charset=utf-8");
connection.setRequestProperty(HTTP_USER_AGENT, mUserAgent);
connection.setRequestProperty(HTTP_HEADER_ACCEPT, "application/json; charset=utf-8");
connection.connect();
output = new PrintWriter(connection.getOutputStream());
JSONObject jsonParam = new JSONObject();
jsonParam.put("oauth_token", params.get("oauth_token"));
jsonParam.put("rating", "1");
jsonParam.put("comments", "ASDASDASDASDASDASDAS");
Log.d(tag, jsonParam.toString());
output.print(jsonParam);
output.flush();
output.close();
Log.d(tag, connection.getResponseCode() + connection.getResponseMessage());
}catch(Exception e ){
}
When I try to send an image in json params, I receive an 500 internal error message.
Thanks!
Okay , as per my suggestion 2 ways to send image to server
use base 64 string
Direct upload to server
1.for base 64 go to below link
Android post Base64 String to PHP
2.for direct upload to server Please check below link
http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/
Happy coding !!
People! After a lot of day, i could upload an image to a server! I was reading this library, which is for a lot of uses. https://source.android.com/reference/com/android/tradefed/util/net/HttpMultipartPost.html
I downloaded the source code, and i took some clases to send an image. I send only bytes, which were encoded from ASCII. Thanks for the help!
Check this below code to send form data and zip file containing images or other any media files.
private class MultipartFormTask extends AsyncTask<String, Void, String> {
String getStringFromInputStream(HttpURLConnection conn) {
String strResponse = "";
try {
DataInputStream inStream = new DataInputStream(
conn.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(
inStream));
String line;
while ((line = br.readLine()) != null) {
strResponse += line;
}
br.close();
inStream.close();
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return strResponse;
}
void uploadJSONFeed(HttpURLConnection conn, DataOutputStream dos,
String lineEnd) {
String issue_details_key = "issue_details";
String issue_details_value = "Place your Jsondata HERE";
try {
dos.writeBytes("Content-Disposition: form-data; name=\""
+ issue_details_key + "\"" + lineEnd
+ "Content-Type: application/json" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(issue_details_value);
dos.writeBytes(lineEnd);
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
}
void uploadZipFile(HttpURLConnection conn, DataOutputStream dos,
String lineEnd) {
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
InputStream is = null;
try {
is = getAssets().open("Test.zip");
} catch (IOException ioe) {
// TODO Auto-generated catch block
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
String zip_file_name_key = "file_zip";
String upload_file_name = "test.zip";
dos.writeBytes("Content-Disposition: form-data; name=\""
+ zip_file_name_key + "\";filename=\""
+ upload_file_name + "\"" + lineEnd); // uploaded_file_name
// is the Name
// of the File
// to be
// uploaded
dos.writeBytes(lineEnd);
bytesAvailable = is.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = is.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = is.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = is.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
is.close();
} catch (IOException ioe) {
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String urlString = "http://www.example.org/api/file.php";
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);
uploadJSONFeed(conn, dos, lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
uploadZipFile(conn, dos, lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
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
String strResponse = getStringFromInputStream(conn);
return strResponse;
}
#Override
protected void onPostExecute(String result) {
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
.show();
Log.e("Result:", result);
}
}
you can upload large jsonstring using buffer please use bellow code .
HttpsURLConnection connection = null;
OutputStream os = null;
InputStream is = null;
InputStreamReader isr = null;
try {
connection = (HttpsURLConnection) url.openConnection();
SSLContext contextSSL = SSLContext.getInstance("TLS");
contextSSL.init(null, new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(contextSSL.getSocketFactory());
MySSLFactory(context.getSocketFactory()));
HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(0);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", auth);
connection.setConnectTimeout(timeoutMillis);
OutputStream os ;
if (input != null && !input.isEmpty()) {
os = connection.getOutputStream();
InputStream stream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8));
BufferedInputStream bis = new BufferedInputStream(stream, 8 * 1024);
byte[] buffer = new byte[8192];
int availableByte = 0;
while ((availableByte = bis.read(buffer)) != -1) {
os.write(buffer, 0, availableByte);
os.flush();
}
}
int responseCode = connection.getResponseCode();
HTTP 500 error code means a server-side error occured.
This has nothing to do with your code.
The server is having a bug, not your code.

Cannot send binary data using multipart form (string params + video param + image param)

I ran into a problem while trying to send some binary files(a 1.44 MB video and a png Image) along with some string params by using multipart-form. The problem is that after writing the headers and all the necessary stuff , when writing bytes on outputstream it blocks me from writing something else .
Can you please tell me what am i doing wrong !!
Here is my AsyncTask that sends data to the server
private class UploadUpAsyncTask extends AsyncTask<String, Void,
String>{
private String path;
private String lineend ="\r\n";
private String boundry = "****";
private String twoHiphens="--";
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
public UploadUpAsyncTask(String path){
this.path =path;
}
#Override
protected String doInBackground(String... urls) {
File file = new File(path);
File image = new File("/storage/emulated/0/DCIM/100MEDIA/error.png");
try {
URL url = new URL(urls[0]);
Log.d("UPLOAD", "URL ="+urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundry);
conn.setRequestProperty("Authorization", "----------------------------");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"user_id\""+lineend+lineend);
out.writeBytes("1"+lineend);
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"preview_id\""+lineend+lineend);
out.writeBytes("1"+lineend);
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"categories_id\""+lineend+lineend);
out.writeBytes("2"+lineend);
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"title\""+lineend+lineend);
out.writeBytes("Mama"+lineend);
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"tags\""+lineend+lineend);
out.writeBytes("mama"+lineend);
out.flush();
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"video\"; filename=\""+file.getName()+"\""+lineend);
out.writeBytes(lineend);
Log.d("UPLOAD", "Titlul video-ului ="+file.getName());
//decoding of bytes from video
FileInputStream file_stream = new FileInputStream(file);
bytesAvailable =file_stream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
buffer = new byte[bufferSize];
Log.d("UPLOAD", "Bytes Read Video =" +bytesRead);
bytesRead = file_stream.read(buffer);
//writting to outputstream
while (bytesRead >0){
out.write(buffer, 0, bytesRead);
bytesRead=file_stream.read(buffer);
}
Log.d("UPLOAD", "Done Loading first buffer");
file_stream.close();
out.writeBytes(twoHiphens+boundry+lineend);
out.writeBytes("Content-Disposition: form-data; name=\"thumb\"; filename=\""+image.getName()+"\""+lineend);
out.writeBytes(lineend);
Log.d("UPLOAD", "Titlul preview-ului ="+image.getName());
//decodint image bytes
FileInputStream image_stream = new FileInputStream(image);
int bytesRead2;
int bytesAvailable2, bufferSize2 ;
bytesAvailable2 = image_stream.available();
bufferSize2 = Math.min(bytesAvailable2, maxBufferSize);
byte []buffer2 = new byte[bufferSize2];
//writing to outputstream
bytesRead2 = image_stream.read(buffer2);
while(bytesRead2>0){
out.write(buffer2, 0, bytesRead2); // bytesAvailable2 = image_stream.available();
bytesRead2 = image_stream.read(buffer2);
}
image_stream.close();
Log.d("UPLOAD", "Done loading the second buffer");
out.writeBytes(twoHiphens+boundry+twoHiphens+lineend);
out.writeBytes(lineend);
out.flush();
out.close();
Log.d("UPLOAD","Response Code = "+conn.getResponseCode());
String responseMessage = conn.getResponseMessage();
Log.d("UPLOAD", "Response Message = "+responseMessage);
InputStream in;
if(conn.getResponseCode() >= 400){
in = conn.getErrorStream();
}else{
in = conn.getInputStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
StringBuilder response = new StringBuilder();
char []bytes = new char[512];
int read ;
while((read = reader.read(bytes))!=-1){
response.append(bytes, 0, read);
}
Log.d("UPLOAD", "Response " +response);
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "maine";
}
#Override protected void onPostExecute(String result) {
super.onPostExecute(result); Log.d("UPLOAD", "Upload complete");
}
}
SOLVED !! The MIME Type selection of the files sent on the server was all wrong !

Upload a image through an HTTP form, via MultipartEntity (how to change media type from application to image)

Here is my code
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.hugosys.in/www.nett-torg.no/api/rpcs/uploadfiles/?");
File file = new File("/mnt/sdcard/xperia.png");
FileBody fileBody = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("post_id", new StringBody("906"));
reqEntity.addPart("user_id", new StringBody("1"));
reqEntity.addPart("files", fileBody);
httpPost.setEntity(reqEntity);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
response_string =convertStreamToString(is);
..........
method to parse response
private static 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 + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
I m getting success from the server, but image is not received on server ... wht i m doing wrong
Apply this
private String doFileUpload()
{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myimage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imagebyte = stream.toByteArray();
System.out.println(imagebyte + "...................................");
String urlString = "your url";
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
MultipartEntity reqEntity = new MultipartEntity();
Calendar cal = Calendar.getInstance();
String image_name = cal.getTime().toString();
image_name = image_name.replace(" ", "");
image_name = image_name.replace(":", "");
image_name = image_name.substring(3, 14);
//userfile
reqEntity.addPart("featured_img", new ByteArrayBody(imagebyte,
"Chasin_" + image_name + "_image.jpg"));
reqEntity.addPart("title", new StringBody(title_var));
reqEntity.addPart("description",new StringBody(description_var));
reqEntity.addPart("category",new StringBody(cat_var));
reqEntity.addPart("tags",new StringBody(tag));
reqEntity.addPart("userid",new StringBody(Constants.USER_ID));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
response_str = EntityUtils.toString(resEntity);
} catch (Exception ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
return response_str;
}
Guys i think i have to work on these things
public void connectForMultipart() throws Exception {
con = (HttpURLConnection) ( new URL(url)).openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
con.connect();
os = con.getOutputStream();
}
public void addFormPart(String paramName, String value) throws Exception {
writeParamData(paramName, value);
}
public void addFilePart(String paramName, String fileName, byte[] data) throws Exception {
os.write( (delimiter + boundary + "\r\n").getBytes());
os.write( ("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + fileName + "\"\r\n" ).getBytes());
os.write( ("Content-Type: application/octet-stream\r\n" ).getBytes());
os.write( ("Content-Transfer-Encoding: binary\r\n" ).getBytes());
os.write("\r\n".getBytes());
os.write(data);
os.write("\r\n".getBytes());
}
public void finishMultipart() throws Exception {
os.write( (delimiter + boundary + delimiter + "\r\n").getBytes());
}
I have changed Content-Type: application/octet-stream\r\n" to Content-Type: image/jpeg\r\n\r\n and it worked :)
File imgFile = new File(Environment.getExternalStorageDirectory() + "/photo1/image2.jpg");
if (imgFile.exists()) {
myimage = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
// im.setImageBitmap(myimage);
}

Categories

Resources