Not Posting image file in android using multipart httppost method

别来无恙 提交于 2019-12-02 07:25:14
Dharma Kshetri

I recently doing just like your problem Here is the Solution:

Image take from sdcard and camera:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Bitmap scaledphoto = null;
        int height = 100;
        int width = 100;
        if (resultCode == RESULT_OK) {
            if (requestCode == SD_REQUEST) {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                yourSelectedImage = BitmapFactory.decodeFile(selectedImagePath);
                scaledphoto = Bitmap.createScaledBitmap(yourSelectedImage,
                        height, width, true);
                pImage.setImageBitmap(scaledphoto);

                Uri selectedImageUri1 = data.getData();
                path = getRealPathFromURI(selectedImageUri1);


            }
            if (requestCode == CAMERA_REQUEST) {
                yourSelectedImage = (Bitmap) data.getExtras().get("data");
                scaledphoto = Bitmap.createScaledBitmap(yourSelectedImage,
                        height, width, true);
                profImage.setImageBitmap(scaledphoto);
                Uri selectedImageUri1 = data.getData();
                path = getRealPathFromURI(selectedImageUri1);

            }
        }

Now you call the Function, where you want to upload pictures:

    String url="http://test.com/uploadimage.php";
    //path is the defined, which is take from camera and sdcard.
   // userid is, which user do you want upload picture.
    UploadImageHttp.sendPost(url, path, userId);

Here is the Class of Upload Image:

public class UploadImageHttp {
public static void sendPost(String url, String imagePath,String userId)
        throws IOException, ClientProtocolException {

    String responseBody;
    HttpClient client = new DefaultHttpClient();
    HttpPost request = new HttpPost(url);

    MultipartEntity entity = new MultipartEntity(
            HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File(imagePath);
    ContentBody encFile = new FileBody(file,"image/png");

    entity.addPart("images", encFile);
    entity.addPart("UserId", new StringBody(userId));

    request.setEntity(entity);



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


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

    }
}

I hope you satisfied for this code.I run successfully.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!