Try to upload the image in php server but it could post. in android

前端 未结 2 1969
旧巷少年郎
旧巷少年郎 2020-12-16 08:27

I try to upload the image in server through the gallery with other entries like name DOB id etc , all the entries are uploaded except image in php server , I did not under s

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 09:27

    Following code will first compress image with resolution, and then set MultiPart entity and send data over web via POST method.

    BitmapFactory.Options options = new BitmapFactory.Options();
    
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = true;
        // image path `String` where your image is located
        BitmapFactory.decodeFile(imagePath, options);
    
        int bitmapWidth = 400;
        int bitmapHeight = 250;
    
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
    
        if (height > bitmapHeight || width > bitmapWidth) {
            if (width > height) {
                inSampleSize = Math
                        .round((float) height / (float) bitmapHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) bitmapWidth);
            }
        }
    
        options.inJustDecodeBounds = false;
        options.inSampleSize = inSampleSize;
    
    
        // you can change the format of you image compressed for what do you
        // want;
        // now it is set up to 640 x 480;
    
        Bitmap bmpScale = BitmapFactory.decodeFile(imagePath, options);
    
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
    
        // CompressFormat set up to JPG, you can change to PNG or whatever you
        // want;
    
        bmpScale.compress(CompressFormat.JPEG, 100, bos);
    
        byte[] data = bos.toByteArray();
    
        MultipartEntity entity = new MultipartEntity(
                HttpMultipartMode.BROWSER_COMPATIBLE);
    
        entity.addPart("avatar", new ByteArrayBody(data,"pic.jpg"
                ));
    
        //add your other name value pairs in entity.
    
        for (int i = 0; i < nameValuePairs.size(); i++) {
            entity.addPart(nameValuePairs.get(i).getName(), new StringBody(
                    nameValuePairs.get(i).getValue()));
        }
    
        httppost.setEntity(entity);
    
        HttpResponse response = httpClient.execute(httppost);
    

    Edit

    Oh.. sorry, i forgot to inform. Yes there is a jar named httpmime-4.2.2 and httpclient.jar. You can download it from Apache Site. Just extract package, and you will get directory of lib.

提交回复
热议问题