如何使用Retrofit/Android将位图发布到服务器

MrR*_*Red 3 android retrofit

我正在尝试使用Android和将位图发布到服务器Retrofit.

目前我知道如何发布文件,但我更喜欢直接发送位图.

这是因为用户可以从他们的设备中挑选任何图像.我想在发送到服务器之前调整它以节省带宽,并且最好不必加载它,调整大小,将其作为文件保存到本地存储然后发布文件.

有人知道如何发布位图Retrofit吗?

Flo*_*lin 16

首先将位图转换为文件

//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();

//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();

//write the bytes in file
FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(f);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        fos.write(bitmapdata);
        fos.flush();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

之后创建一个请求,Multipart以便上传您的文件

RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), f);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload", f.getName(), reqFile);
Run Code Online (Sandbox Code Playgroud)

您的服务电话应如下所示

interface Service {
    @Multipart
    @POST("/yourEndPoint")
    Call<ResponseBody> postImage(@Part MultipartBody.Part image);
}
Run Code Online (Sandbox Code Playgroud)

然后打电话给你的api

Service service = new Retrofit.Builder().baseUrl("yourBaseUrl").build().create(Service.class);
Call<okhttp3.ResponseBody> req = service.postImage(body);
req.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 
         // Do Something with response
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        //failure message
        t.printStackTrace();
    }
});
Run Code Online (Sandbox Code Playgroud)