1

I'm trying to upload an image using the following code:

  HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(
                    "http://konsole-data.de/uploadtest/upload.php");

            MultipartEntity multiPart = new MultipartEntity();
            multiPart.addPart("picture", new FileBody(new File(path)));

            httpPost.setEntity(multiPart);
            try {
                HttpResponse res = httpClient.execute(httpPost);

                            Toast.makeText(getApplicationContext(),res.toString(),
                        Toast.LENGTH_LONG).show();
            } catch (ClientProtocolException e) {

                e.printStackTrace();
            } catch (IOException e) {

                e.printStackTrace();
            }

path is a String which identifies the image like /mnt/sdcard/DCIM/12712.jpg The connection works BUT no image is uploaded to the server, you can see a debug file here: http://konsole-data.de/uploadtest/data/20121214-144802-.dbg
What am doing wrong?

1 Answer 1

2

You should probably specify the HttpMultipartMode, and the MIME type of the file (but this is not necessary i think):

MultipartEntity multipart = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

FileBody bin = new FileBody(new File(path), "image/jpeg");
multipart.addPart("picture", bin);

EDIT:

You should also check if you use the right path. Instead of creating the File object as an anonymous inner class:

File file = new File(path);
if(file.exists()){
    FileBody bin = new FileBody(file, "image/jpeg");
    multipart.addPart("picture", bin);
} else {
    Log.w(YourClass.class.getSimpleName(), "File " + path + " doesn't exist!");
}
Sign up to request clarification or add additional context in comments.

10 Comments

just added that.. Still can't get the image uploaded: POST: a:0:{} FILES: a:0:{}
The code seems ok. I use the same method to upload pictures in one of my projects. Are you sure that you have the right path for the image?
yep, I used Toast to check that. Path was mnt/sdcard/DCIM/Camera/162533.jpg
That path is wrong. It's '/mnt/sdcard/...'. You should check with File.exists() if you are looking at the right places.
thanks. The file exists, I forgot to say that I use the same path to create an image preview in the same activity, but I still can't manage the upload.. POST: a:0:{} FILES: a:0:{} Can the reason be that the php script cant handle the file correctly? Thought when I select an image from PC it works fine
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.