2

I have been headache , how to upload image in to server.It is new task for me.but big confusing for me.i searched on stackoverflow and googled. but i getting problems.

My intention is Upload photo from sdcard and take photo from camera and upload to server.

In ios, this task already done, in ios php get this type of: When posting php side simple hit this information.

and Print Like this;

$filedata = $_FILES['photos'];
$f = fopen(time().".txt",'wb');
fwrite($f, print_r($_REQUEST,true));
fclose($f);

   [photos] => Array
        (
            [name] => game.png
            [type] => image/png
            [tmp_name] => /tmp/phpiQHIXQ
            [error] => 0
            [size] => 1664972
        )

What I do.

   // yourSelectedImage is the bitmap image.
    public void SaveImage() throws Exception {
            try {
                 String url = "http://test.com/uploadImage.php";
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                yourSelectedImage.compress(CompressFormat.PNG, 75, bos);
                byte[] data = bos.toByteArray();
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost postRequest = new HttpPost(url);
                
                ByteArrayBody bab = new ByteArrayBody(data, "image/jpeg");
              
                MultipartEntity reqEntity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);
                reqEntity.addPart("photos", bab);
            
                postRequest.setEntity(reqEntity);
                HttpResponse response = httpClient.execute(postRequest);
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent(), "UTF-8"));
                String sResponse;
                StringBuilder s = new StringBuilder();
     
                while ((sResponse = reader.readLine()) != null) {
                    s = s.append(sResponse);
                }
                System.out.println("Response: " + s);
            } catch (Exception e) {
                // handle exception here
                Log.e(e.getClass().getName(), e.getMessage());
            }
        }

In Php Server, Getting like this

$filedata = $_FILES['photos'];

and further function done in php.

But I am not posting using httppost in to the multipart above type of structure of file, where file includes image name, image type,temp name, and others.

Edited:

I have Change Little bit Code:, But failed to post image file information php server, userid ok but image file information could not post.In this case, Image save successfully on server, i could not get information on php sever of image.

Here is the Code:

public class UploadImageHttpPost {

String testpath="/mnt/sdcard/14111.jpg";
String url = "http://test.com/uploadImage.php";

public static void sendPost(String url, String imagePath,String userId)
        throws IOException, ClientProtocolException {
    Log.w("TAG", "Start Upload" );
    Log.w("TAG", "URL-> "+url );
    Log.w("TAG", "Image Path-> "+imagePath );
    Log.w("TAG", "User Id-> "+userId );
    String responseBody;

    MultipartEntity entity = new MultipartEntity(
            HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File(imagePath);
    FileBody encFile = new FileBody(file,"image/jpeg");
    Log.w("TAG", "image file-> "+encFile );
    entity.addPart("photos", encFile);
    entity.addPart("UserId", new StringBody(userId));
    HttpPost request = new HttpPost(url);
    request.setEntity(entity);
    
    HttpClient client = new DefaultHttpClient();

    ResponseHandler<String> responsehandler = new BasicResponseHandler();
    responseBody = client.execute(request, responsehandler);

    if (responseBody != null && responseBody.length() > 0) {
        Log.w("TAG", "Response from image upload->" + responseBody);

    }
}

I get Like this:

Array
(
    [UserId] => 914
)

But here below part missing means i am not getting, is there any missing code in multipart post method please check above java code:

[photos] => Array
        (
            [name] => game.png
            [type] => image/png
            [tmp_name] => /tmp/phpiQHIXQ
            [error] => 0
            [size] => 1664972
        )

Would you please correct me, How to post on php, above information of image.

Community
  • 1
  • 1
Horrorgoogle
  • 7,858
  • 11
  • 48
  • 81

2 Answers2

1

Try this one :

File file = new File(_filePath);
MultipartEntity multipart = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipart.addPart("file", new FileBody(file));

DefaultHttpClient httpClient = new DefaultHttpClient();

HttpResponse res;
URI uri = new URI(url.php);


HttpPost methodpost = new HttpPost(uri);
methodpost.addHeader("pragma","no-cache");
methodpost.setEntity(multipart);
res = httpClient.execute(methodpost);

InputStream data = res.getEntity().getContent();

Sure, to complete with what you need.

Hope this helps.

shemsu
  • 1,066
  • 9
  • 17
1

Upload image using Multipart entity

    File file1 = null;
    FileBody bin1 = null;    

    HttpPost postRequest = new HttpPost(url);

      // uri for your image path   
                   if(uri != null)
                   {   
                       file1 = new File(getPath(uri));

                       bin1 = new FileBody(file1);
                   }


           MultipartEntity reqEntity = new MultipartEntity();



                   if(bin1!=null)
                       reqEntity.addPart("profile_image", bin1);


                   post.setEntity(reqEntity);


                     HttpResponse httpResponse = client.execute(post);

                     int mResponse_code =  httpResponse.getStatusLine().getStatusCode();


                     resEntity = httpResponse.getEntity();



                     response = EntityUtils.toString(resEntity);

And Parse your json response. It is very simple way.

Newts
  • 1,354
  • 14
  • 23