I have been using this code, but have been running into some memory issues:
// Get the image from the sdcard
Bitmap bm = BitmapFactory.decodeFile("/sdcard/myimage.jpg");
// turn image into byte array output stream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 'compress' the jpeg
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
// get byte[] array of the image
byte[] byteArray = baos.toByteArray();
// turn image into base64 string
String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
// and base64 string to 'params' value pair
params.add(new BasicNameValuePair("userfile", encodedImage));
try {
HttpPost request = new HttpPost();
String urlString = "http://www.example.com";
request.setURI(new URI(urlString));
if(params != null) {
request.setEntity(new UrlEncodedFormEntity(params));
HttpClient client = new DefaultHttpClient();
client.execute(request);
} // end if
} // end try
It has been suggested that I should use Base64OutputStream instead of Base64.encodeToString , but I have not been successful in using Base64OutputStream outputting a string that I can upload to the server. Any examples of using Base64OutputStream on an IMAGE would be a great help.
EDIT
To make the answer work, You need to add two files to your Android project: apache-mime4j-dom-0.7.2.jar and httpmime-4.1.3.jar;
You can download apache-mime4j-dom-0.7.2.jar from http://james.apache.org/download.cgi#Apache_Mime4J - download the binary, unzip it, and find the apache-mime4j-dom-0.7.2.jar file.
Then go to http://grepcode.com/snapshot/repo1.maven.org/maven2/org.apache.httpcomponents/httpmime/4.1.3 and download httpmime-4.1.3.jar
Then drag both those files into your project in Eclipse. Then in Eclipse, choose Project > Properties. Select the Properties Pop-up, select Java Build Path. Click the "Libraries" tab (Look for Source | Projects | Libraries | Order and Export). Click "Add Jars" and selectapache-mime4j-dom-0.7.2.jar and httpmime-4.1.3.jar; Then click the "Order and Export" tab. Check apache-mime4j-dom-0.7.2.jar and httpmime-4.1.3.jar; Then close that popup and choose Project > Clean from the Eclipse menu.
If possible, you should not base64encode your files and send them in URL, but use MultiPart file upload instead:
HttpPost post = new HttpPost(URL);
HttpClient client = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
// picture
entity.addPart( "userfile", new FileBody(
new File( MyApp.getContext().getFilesDir(), "userfile.jpg" ),
"image/jpeg")
);
entity.addPart( "blahblah", new StringBody( "blah" )); // string value
post.setEntity( entity );
client.execute( post );
Related
I need to upload Image and Video File with multiple parameters like File Name, Description , Height and Width using HttpPost method.
Thanks,
Suggestion appreciated.
For uploading a file the efficient way is using HttpPost with multipart/form
Multipart/form The file contents are either stored in memory or temporarily on disk. In either case, the user is responsible for copying file contents to a session-level or persistent store as and if desired. The temporary storages will be cleared at the end of request processing
Refer this Upload Files from Android to a Website/Http Server using Post
try this code
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
//Path of the file to be uploaded
String filepath = params[0];
File file = new File(filepath);
ContentBody cbFile = new FileBody(file, SET_MIMETYPE);//"audio/basic"
try {
mpEntity.addPart(FILE_NAME, cbFile);
post.setEntity(mpEntity);
HttpResponse response1 = client.execute(post);
HttpEntity resEntity = response1.getEntity();
} catch (Exception e) {
e.printStackTrace();
}
or also refer this link
"http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/"
Thanks
Here is the code...
Bitmap bm = myImageToUpload;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(myServerURL);
ByteArrayBody bab = new ByteArrayBody(data, imageName);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploadedfile", bab);
reqEntity.addPart("fileName", new StringBody("image"));
reqEntity.addPart("mimeType", new StringBody("images/jpeg"));
reqEntity.addPart("extraInfo", new StringBody(extraInfo));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
This code uploads my image along with some other information to the server. Is there a better way to do this?
My concerns - It is slow, Sometimes takes 20 minuets to upload a large image to the server. The size of the image on the server is larger than the original.
at the very least, how can I upload the image so that the image on the server is the exact same size as the image on my android device?
reqEntity.addPart("uploadedfile", new FileBody(new File(myImageToUpload)));
This might be faster, and reads more easily, unless you really need the byte array.
I write app on android which will send xml file to PHP server. Here is my code:
InputStream is = new FileInputStream(file);
HttpClient httpClient = new DefaultHttpClient();
HttpPost postReq = new HttpPost("http://majkelsoftgames.cba.pl/ser/server.php");
byte[] data = IOUtils.toByteArray(is);
InputStreamBody isb= new InputStreamBody(new ByteArrayInputStream(data), "file");
MultipartEntity multipartContent = new MultipartEntity();
multipartContent.addPart("file", isb);
postReq.setEntity(multipartContent);
HttpResponse response = httpClient.execute(postReq);
My problem is that when
byte[] data = IOUtils.toByteArray(is);
is executing I get:
java.lang.NoClassDefFoundError: org.apache.commons.io.IOUtils
I downloaded external commons-io.jar from http://commons.apache.org/io/ and added this jar to the java build path in android project. I really have no idea what I am doing wrong. Do you have any idea how can I fix it?
You added it to the build path, but did you place it in the /libs directory of youur project? That is the only way it will get added to your apk.
I tried to download [httpmime-4.0.1.jar] but still the error is there and -------------------------------
class ImageUploadTask extends AsyncTask {
#Override
protected String doInBackground(Void... unsued) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(getString(R.string.WebServiceURL) + "/cfc/iphonewebservice.cfc?method=uploadPhoto");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("photoId", new StringBody(getIntent()
.getStringExtra("photoId")));
entity.addPart("returnformat", new StringBody("json"));
entity.addPart("uploaded", new ByteArrayBody(data,"myImage.jpg"));
entity.addPart("photoCaption", new StringBody(caption.getText().toString()));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
Add a libs folder in your application then add “httpmime-4.1.3.jar”, after that you need to show this directory to your project properties.
You should add this JAR to build path. If you are using Eclipse just copy it to project folder. Then in Eclipse right mouse click on it, BUILD PATH->ADD TO BUILD PATH
I am trying to upload image on web server, but whenever it tries it is sending me html source code as response and image is not uploaded there. My code is:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
bitMap.compress(Bitmap.CompressFormat.JPEG, 100, byteStream);
byte[] buffer = byteStream.toByteArray();
ByteArrayBody body = new ByteArrayBody(buffer,"profile_image");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("b#gmail.com.jpg", body);
post.setEntity(entity);
System.out.println("post entity length "+entity.getContentLength());
ResponseHandler handler = new BasicResponseHandler() ;
String response = client.execute(post,handler);
Thanks in advance!!!
Look at this Example http://vikaskanani.wordpress.com/2011/01/11/android-upload-image-or-file-using-http-post-multi-part/
And change YourUrl