Upload multipart image data in JSON with Retrofit?

痞子三分冷 提交于 2019-12-01 00:57:46

问题


I would like to do a PUT request with this JSON body (containing a picture) and with Retrofit. I'm using it under Android:

{
    "Request": {
        "data": {
            "Key": "keydata",
            "param": {
                "title": "Testingpostmultipartimageupload",
                "photo": **"IMAGE BYTE DATA"**
            }
        }
    }
}

Any clues?


回答1:


Ok, I found a solution using multipart, somethings like that:

@Multipart
@PUT("/users/{id}")
void modifyPic(
    @Header("auth_token") String token,
    @Path("id") int userid,
    @Part("request[data][param][title]") String title,
    @Part("request[data][param][Photo]") TypedFile avatar,
    Callback<User> cb
);



回答2:


You need to put image data in byte by using multipart form data.

try {
    HttpPost httppost = new HttpPost("some url");
    MultipartEntity multipartEntity = 
        new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
    multipartEntity.addPart("Image", new FileBody(image));
    httppost.setEntity(multipartEntity);
    mHttpClient.execute(httppost, new YOURHANDLER());
} catch (Exception e) {
    Log.e(ServerCommunication.class.getName(), e.getLocalizedMessage(), e);
}

To send post request using parameters

HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

if (values != null) {
    for (Map.Entry<String, String> entry : values.entrySet()) {
        nameValuePairs.add(
            new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
}



回答3:


Retrofit only takes multipart and requestbody for its multipart.

Call<SubmitLevel1Part2IconResp> loadLevel1halfIconswithImage(@Part("headerdata[relation][icon_type]") RequestBody icon_type, @Part("headerdata[relation][name]") RequestBody name, @Part MultipartBody.Part file);

And then in java

 // MultipartBody.Part is used to send also the actual filename
 MultipartBody.Part body =  MultipartBody.Part.createFormData("headerdata[relation][relative_image]", fileUpload.getName(), requestFile);



call = service.loadLevel1halfIconswithImage(icon_type, name, body);


来源:https://stackoverflow.com/questions/24165605/upload-multipart-image-data-in-json-with-retrofit

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