Reputation: 1
I've been researching this topic for a while and I'm getting nowhere. The books that I bought and every example/blog I find explain how to use the HttpClient, HttpPost and MultipartEntity objects to upload files. Whenever I use this method, 1 of several things happens to me:
My application will crash. Android tells me that the application stopped unexpectedly and I have to force it to close.
If I use code, which contains MultipartEntity, without including the image file (using addPart()), the POST data is received by my PHP server.
I need a simple and straight-forward way of accomplishing this procedure. I even experimented with FTP and I will try to use the FTPClient example code that I have, but so far I am getting nowhere and usually uploading files is a very simple task.
If there is anyone out there who can help me, please send me a reply. The hardest part of this project is understanding proper procedure because I find a lot of different types of code from almost each source I see online. It seems as if there is no standard for this subject, which is highly frustrating.
Upvotes: 0
Views: 502
Reputation: 11
Make sure you set your permissions in the xml file. Usually opening sockets and sending data requires you to set a higher level of permission on the app than just the default
Upvotes: 1
Reputation: 21343
I've used this block of code in several of my Android project and it hasn't caused any problem. You can modify it as needed. It uses HttpMime-4.1.1 and it is part of the HttpCore. Hopefully it will work for you as well
/***
* Execute multi part request especially for thing related to byte[]
* @param url The destination URL
* @param byteArray The byte to upload
* @param values Additional key/value pair that you want to add
* @param fileImage The image file name
* @param imageFileKey The form key for the bytes that you are uploading
* @return
* @throws Exception
*/
public static HttpResponse executeMultipartPost(String url, byte[] byteArray,
HashMap<String, StringBody> values,
String fileImage, String imageFileKey)throws Exception {
HttpPost postRequest = new HttpPost(url);
HttpClient httpClient = new DefaultHttpClient();
Set<Map.Entry<String, StringBody>> entries = values.entrySet();
MultipartEntity multipartContent = new MultipartEntity();
for(Map.Entry<String, StringBody> current : entries) {
multipartContent.addPart(current.getKey(), current.getValue());
}
InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(byteArray),
"image/jpeg", fileImage);
multipartContent.addPart(imageFileKey, isb);
postRequest.setEntity(multipartContent);
HttpResponse res = httpClient.execute(postRequest);
return res;
}
Upvotes: 1
Reputation: 4747
You seem to have nearly all the weapons already ; are you sending the POST request from a new thread though? I'm guessing you're not and that would be the reason of force close (ie hanging on the main thread of your application).
If that's not it, could you show some code?
Upvotes: 0