I am trying to have my application upload images to the webserver using the code below. It works sometimes, but also seems to fail with a memory error. Can someone please post an example of how to accomplish this if the file size is to big? Also, I am building this to support 1.5 and up. I don't mind if the code given to me resizes the image smaller before upload.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlString);
File file = new File(nameOfFile);
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamEntity reqEntity = new InputStreamEntity(fileInputStream, file.length());
httppost.setEntity(reqEntity);
reqEntity.setContentType("binary/octet-stream");
HttpResponse response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
responseEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
You have two option to make your code workable.
You should use multi part approach to upload larger size file. Which i am using in my code.
Its Apache code. (Yes, you can easily port it in your Android project).
You can minimize the image resolution. by using SampleSize flag,
Follow this link.
I hope it help.
You can try following code for uploading images.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntity multiPart = new MultipartEntity();
multiPart.addPart("my_picture", new FileBody(new File(IMG_URL)));
httpPost.setEntity(multiPart);
HttpResponse res = httpClient.execute(httpPost);
you should really look into setChunkedStreamingMode of the connection. or, indeed, use MultipartEntity (it's apache httpcomponents library - you will easily find lots of solutions on this.
as for resizing images, it's quite simple:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2; // look at the link Rajnikant gave for more details on this
Bitmap bitmap = BitmapFactory.decodeFile(filename, options);
// here you save your bitmap to whatever you want
but it is memory consuming too...
Related
I m using the following code to upload file to a server. It works quite well in localhost and bluehost. But it is not working in some hosting like(Go Daddy). Would anybody explain why???
data = IOUtils.toByteArray(inputStream);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(upload_url);
InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), fileName);
CustomMultiPartEntity multipartEntity = new CustomMultiPartEntity();
multipartEntity.setUploadProgressListener(this);
multipartEntity.addPart("pdf", inputStreamBody);
multipartEntity.addPart("title", new StringBody(title));
multipartEntity.addPart("subject", new StringBody(subject));
multipartEntity.addPart("college", new StringBody(college));
multipartEntity.addPart("stream", new StringBody(stream));
multipartEntity.addPart("branch", new StringBody(branch));
multipartEntity.addPart("userID", new StringBody(String.valueOf(userid)));
httpPost.setEntity(multipartEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
I performed a lot of testing. When I retrieve the values via $_POST[] in the server, the value is null. HttpUrlConnection works in all server. But we have to write everything ourselves. I mean why to write so much code from scratch for a simple function like upload... Is there no library with simple callbacks.?
HttpClient, HttpPost.. are deprecated in API 22, So you should try to use HttpURLConnection instead.
I'd like create a method for uploading image from Android to a REST Server through POST method.
Is the following code I wrote right?
Thank you in advance!
my code:
//Creating multi part http connection in post mode
HttpPost request = new HttpPost("url-to-my-server");
//Server header specs
request.setHeader("Accept","application/json");
request.setHeader("content-type","multipart/form-data");
request.setHeader("username",username);
request.setHeader("usertoken",token);
//Create entity parts
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addTextBody("param1","par1", ContentType.TEXT_PLAIN);
multipartEntity.addTextBody("param2","par2", ContentType.TEXT_PLAIN);
multipartEntity.addTextBody("param3","par3", ContentType.TEXT_PLAIN);
multipartEntity.addTextBody("param4","par4", ContentType.TEXT_PLAIN);
//Add image
File fileImg = new File(picName);
multipartEntity.addBinaryBody("image",fileImg,ContentType.create("image/jpeg"),picName);
request.setEntity(multipartEntity.build());
httpclient.execute(request, retFunc);
I was following this tutorial to upload images with android: here
After the line conn.setRequestProperty("uploaded_file", fileName); in function uploadFile(String sourceFileUri) I added further lines with conn.setRequestProperty("title", "example"); conn.setRequestProperty("name", "simple_image"); but in the php file I am not receiving these strings with $_POST or $_GET only the image is uploaded.
Is this tutorial here only for uploading images?
I would like to send with the image some other data too. How could I do this?
Thank you
Yes that tutorial is for uploading a single file only.If you want to send some other data(may be some strings) along with your image, then you can use MultipartEntityBuilder.However to use this you need to download the jars from the Apache HttpComponents site and add them to project and path(just add the httpclient jar to your libs folder).
Now for uploading an image along with some string data you can use (may be inside doInBackground of your AsynTask)
File file = new File("yourImagePath");
String urlString = "http://yoursite.com";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
/* setting a HttpMultipartMode */
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
/* adding an image part */
FileBody bin1 = new FileBody(file);
builder.addPart("uploadedfile1", bin1);
builder.addPart("user", new StringBody("Some String",ContentType.TEXT_PLAIN));//adding a string
HttpEntity reqEntity = builder.build();
post.setEntity(reqEntity);
HttpEntity resultEntity = httpResponse.getEntity();
String result = EntityUtils.toString(resultEntity);
P.S : I assumed you are using AsyncTask for uploading process and that's the reason i said to use this code inside doInBackground of your AsyncTask.
You can use MultipartEntity too.Follow this tutorial which describes how to upload multiple images along with some other string data using MultipartEntity.However there's not much difference in the implementation of MultipartEntity and MultipartEntityBuilder.Try yourself to learn both.Hope these info help you.
I have a method to send image and text as a HttpPost using MultipartEntity content type. Everything works great with English symbols, but for unicode symbols (for example Cyrliics) it sends only ???. So, I'm wondering, how to set UTF-8 encoding for MultipartEntity correctly, since I've tried several sulutions, suggested on SO, but none of them worked.
Here what I have already:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
mpEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mpEntity.setCharset(Consts.UTF_8);
mpEntity.addPart("image", new FileBody(new File(attachmentUri), ContentType.APPLICATION_OCTET_STREAM));
ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
StringBody stringBody = new StringBody(mMessage, contentType);
mpEntity.addPart("message", stringBody);
final HttpEntity fileBody = mpEntity.build();
httpPost.setEntity(fileBody);
HttpResponse httpResponse = httpclient.execute(httpPost);
UPD
I tried to use InputStream as per #Donaudampfschifffreizeitfahrt suggestion. Now I'm getting ��� characters.
InputStream stream = new ByteArrayInputStream(mMessage.getBytes(Charset.forName("UTF-8")));
mpEntity.addBinaryBody("message", stream);
Also tried:
mpEntity.addBinaryBody("message", mMessage.getBytes(Charset.forName("UTF-8")));
I solved it a different way, using:
builder.addTextBody(key, שלום, ContentType.TEXT_PLAIN.withCharset("UTF-8"));
You can use below line for add part in multipart entity
entity.addPart("Data", new StringBody(data,Charset.forName("UTF-8")));
to send unicode in request.
To the ones who stuck with this issue, this is how I resolved it:
I investigated apache http components libraries source code and found following:
org.apache.http.entity.mime.HttpMultipart::doWriteTo()
case BROWSER_COMPATIBLE:
// Only write Content-Disposition
// Use content charset
final MinimalField cd = part.getHeader().getField(MIME.CONTENT_DISPOSITION);
writeField(cd, this.charset, out);
final String filename = part.getBody().getFilename();
if (filename != null) {
final MinimalField ct = part.getHeader().getField(MIME.CONTENT_TYPE);
writeField(ct, this.charset, out);
}
break;
So, seems like it is some kind of bug / feature in apache lib, which only allowes to add Content-type header to one part of MultipartEntity, if this part has filename not null. So I modified my code as:
Charset utf8 = Charset.forName("utf-8");
ContentType contentType = ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), utf8);
ContentBody body = new ByteArrayBody(mMessage.getBytes(), contentType, "filename");
mpEntity.addPart("message", body);
And Content-type header appeared for string part, and symbols are now encoded and decoded correctly.
As part of my Android app, I'd like to upload bitmaps to be remotely stored. I have simple HTTP GET and POST communication working perfectly, but documentation on how to do a multipart POST seems to be as rare as unicorns.
Furthermore, I'd like to transmit the image directly from memory, instead of working with a file. In the example code below, I'm getting a byte array from a file to be used later on with HttpClient and MultipartEntity.
File input = new File("climb.jpg");
byte[] data = new byte[(int)input.length()];
FileInputStream fis = new FileInputStream(input);
fis.read(data);
ByteArrayPartSource baps = new ByteArrayPartSource(input.getName(), data);
This all seems fairly clear to me, except that I can't for the life of me find out where to get this ByteArrayPartSource. I have linked to the httpclient and httpmime JAR files, but no dice. I hear that the package structure changed drastically between HttpClient 3.x and 4.x.
Is anyone using this ByteArrayPartSource in Android, and how did they import it?
After digging around in the documentation and scouring the Internet, I came up with something that fit my needs. To make a multipart request such as a form POST, the following code did the trick for me:
File input = new File("climb.jpg");
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost:3000/routes");
MultipartEntity multi = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
String line;
multi.addPart("name", new StringBody("test"));
multi.addPart("grade", new StringBody("test"));
multi.addPart("quality", new StringBody("test"));
multi.addPart("latitude", new StringBody("40.74"));
multi.addPart("longitude", new StringBody("40.74"));
multi.addPart("photo", new FileBody(input));
post.setEntity(multi);
HttpResponse resp = client.execute(post);
The HTTPMultipartMode.BROWSER_COMPATIBLE bit is very important. Thanks to Radomir's blog on this one.
try this:
HttpClient httpClient = new DefaultHttpClient() ;
HttpPost httpPost = new HttpPost("http://example.com");
MultipartEntity entity = new MultipartEntity();
entity.addPart("file", new FileBody(file));
httpPost.setEntity(entity );
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
Log.e("ClientProtocolException : "+e, e.getMessage());
} catch (IOException e) {
Log.e("IOException : "+e, e.getMessage());
}
Perhaps you can do following step to import library into your Android.
requirement library
- apache-mime4j-0.6.jar
- httpmime-4.0.1.jar
Right click your project and click properties
select java build path
select tab called "Order and Export"
Apply it
Fully uninstall you apk file with the adb uninstall due to existing apk not cater for new library
install again your apk
run it
Thanks,
Jenz
I'm having the same problem. I'm trying to upload an image through MultiPart Entity and it seens that the several updates on HttpClient/MIME are cracking everything. I'm trying the following code, falling with an Error "NoClassDefFoundError":
public static void executeMultipartPost(File image, ArrayList<Cookie> cookies, String myUrlToPost) {
try {
// my post instance
HttpPost httppost = new HttpPost(myUrlToPost);
// setting cookies for the connection session
if (cookies != null && cookies.size() > 0) {
String cookieString = "";
for (int i=0; i<cookies.size(); ++i) {
cookieString += cookies.get(i).getName()+"="+cookies.get(i).getValue()+";";
}
cookieString += "domain=" + BaseUrl + "; " + "path=/";
httppost.addHeader("Cookie", cookieString);
}
// creating the http client
HttpClient httpclient = new DefaultHttpClient();
// creating the multientity part [ERROR OCCURS IN THIS BELLOW LINE]
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("photoupload", new FileBody(image));
httppost.setEntity(multipartEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
} catch (Exception e) {}
}
This method is fully compilable and uses the httpclient-4.0.1.jar and httpmime-4.2.jar libs, but again, I remember that it crashs in the commented line for me.