简体   繁体   中英

How to send class which contain Image from Android to Java Restful Web server using Retrofit

我使用 Retrofit 将数据(类)从 android 传输到服务器。通常我们在客户端和服务器端创建相同的类,其中包含双方相同的数据类型,如 int、String。现在我需要将类中的图像发送到服务器。另外我只是不想将图像发送到服务器,但我想发送包含 1 个图像作为数据类型的类。那么我该怎么做?或者有什么建议我怎么能用其他工具做到这一点?

Suppose you already have a File pointing to the image:

final File imageFile = ...;

Note: How to get this file depends on whether you only allow local files in your file chooser (or eg images that are actually in Google Drive) and on which Android version you are on, etc.

To upload the image you need to use Retrofit's TypedFile - here is what worked for me:

@POST("/api/image/upload")
@Multipart
public void submitPictureToVoting(@Part("user_id") Integer userId,
                                  @Part("image_title") String imageTitle,
                                  @Part("file") TypedFile file,
                                  Callback<UploadImageResponse> callback);

And then:

final TypedFile typedImageFile = new TypedFile("application/octet-stream", imageFile);

mApiClient.submitPictureToVoting(
    1234567,
    "This is me!",
    typedImageFile,
    new Callback<UploadImageResponse> {
        // ...
    });

I dont think this is answer but by doing this we can solve proble of Retrofit easily

Hi I tried this by Encoding Image to String ,so that we can easily send this "String" data type like other String, & when we want image back,we can decode it.

1.Code for Encoding

Here Image taken from ImageView.

BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();

ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);

2.Code for Decoding

 byte[] decodedByte = Base64.decode(encodedImage, 0);
 Bitmap decodedImg= BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
 imageView.setImageBitmap(decodedImg);
  

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