简体   繁体   中英

How to upload image using MultipartEntity in Android HttpPost?

Image not upload using MultipartEntity.

Gives status code 200 but image not updated on serverside.

 String responseBody;
            HttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost(
                    "http__zz/upload_picture?key=abc&property_id=10");

            MultipartEntity entity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);

            File file = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DCIM).toString()
                    + "/Camera/Test.jpg");
            ContentBody encFile = new FileBody(file, "image/png");

            entity.addPart("picture", encFile);

            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);

            }

Try using a ByteArrayBody instead of a FileBody :

File file = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DCIM).toString()
                    + "/Camera/Test.jpg");
Bitmap b = BitmapFactory.decodeFile(file;
ByteArrayOutputStream bao = new ByteArrayOutputStream();
b.compress(CompressFormat.JPEG, 100, bao);

ByteArrayBody body = new ByteArrayBody(bao.toByteArray(), "image/jpeg", "picture");
entity.addPart("picture", body);

为什么不尝试将其作为base64编码的字符串发送?

the best way to do this is to implement an IntentService and notify status with broadcast intents. please check out this code from git its work for me

https://github.com/alexbbb/android-upload-service

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM