用@multipart改造@body有问题

时间:2016-05-06 12:24:24

标签: android annotations retrofit2

类型对象中的图像多部分。

案例1.(我做过的)

服务参数:

{"id":"1","name":"vishal","image/file":""} 

那时我的API Retrofit

@Multipart
@POST("webservice")
Call<SignUpResp> loadSignupMultipart(@Part("description") RequestBody description, @Part MultipartBody.Part file, @QueryMap HashMap<String, String> params);

案例2.(我遇到问题)@Body class<UploadwithImage>

{
    "methodName":"submitLevel1Part2Icon",
    "userid":"150",
    "headerData":{
        "fiction":{
            "icon_type":"1",
            "icon_id":"3"},
        "nonfiction":{
            "icon_type":"2",
            "icon_id":"4"},
        "relation":{
            "icon_type":"3",
            "icon_id":"0",
            "name":"Ronak",
            "relative_image":"<File>",
            "relation_id":"3"},
        "self":{
            "icon_type":"4",
            "icon_id":"0"}
    }
}

我正在尝试API

 @Multipart
 @POST("webservice")
 Call<SubmitLevel1Part2IconResp> loadLevel1halfIconswithImage(@Part("description") RequestBody description, @Part MultipartBody.Part file, @Body UploadwithImage uploadImage);

Java方

    /**
     * code for multipart
     */
     // create RequestBody instance from file
     RequestBody requestFile =  RequestBody.create(MediaType.parse("multipart/form-data"), fileUpload);

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

     // add another part within the multipart request
     String descriptionString = "hello, this is description speaking";
     RequestBody description = RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);

    call = service.loadLevel1halfIconswithImage(description, body, levelOneHalfIcons);

我不知道为什么,但它会返回错误,如:

  

&#34; @Body参数不能与表单或多部分编码一起使用&#34;

任何帮助都会受到赞赏。

8 个答案:

答案 0 :(得分:7)

将您的方法更改为

@Multipart
@POST("users/{id}/user_photos")
Call<models.UploadResponse> uploadPhoto(@Path("id") int userId, @PartMap Map<String, RequestBody> params);

现在创建您的请求参数,

//All the String parameters, you have to put like
Map<String, RequestBody> map = new HashMap<>();
map.put("methodName", toRequestBody(methodName));
map.put("userid", toRequestBody(userId));
map.put("relation", toRequestBody(relation));
map.put("icon_type", toRequestBody(iconType));
map.put("icon_id", toRequestBody(iconId));
map.put("name", toRequestBody(name));
map.put("relation_id", toRequestBody(relationId));

//To put your image file you have to do
File file = new File("file_name");
RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), file);
map.put("relative_image\"; filename=\"some_file_name.png\"", fileBody);

// This method  converts String to RequestBody
public static RequestBody toRequestBody (String value) {
    RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value);
    return body ;
}

//To send your request
call = service.loadLevel1halfIconswithImage(description, params);

如果您不想使用PartMap,只需将它们作为参数传递即可。检查我的回答https://stackoverflow.com/a/37052548/1320616,以获得有关发送带有请求的图像文件的线索。

答案 1 :(得分:7)

简单来说,我这样做了:

我通过更改

tested
Call<Result> resultCall = service.uploadImage(body); 

Call<Result> resultCall = service.uploadImage(body, result); 结果

我的API的

Result.java 类(响应):

public class Result {

    @SerializedName("result")
    @Expose
    private String result;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @SerializedName("value")
    @Expose
    private String value;

    /**
     * @return The result
     */
    public String getResult() {
        return result;
    }

    /**
     * @param result The result
     */
    public void setResult(String result) {
        this.result = result;
    }

}

并创建了对象:

Result result = new Result();
result.setResult("success");
result.setValue("my value");

您可以根据需要更改课程,然后在发送请求时传递对象。因此,您的 ApiService 类就像:

<强> ApiService.java

/**
 * @author Pratik Butani on 23/4/16.
 */
public interface ApiService {

    /*
    Retrofit get annotation with our URL
    And our method that will return us the List of Contacts
    */
    @Multipart
    @POST("upload.php")
    Call<Result> uploadImage(@Part MultipartBody.Part file, @Part("result") Result result);

}

和我的PHP代码是:

<?php

    $file_path = "";
    $var = $_POST['result']; //here I m getting JSON

    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        $result = array("result" => "success", "value" => $var);
    } else{
        $result = array("result" => "error");
    }

    echo json_encode($result);

?>

希望它会对你有所帮助。谢谢。

答案 2 :(得分:1)

我们可以在多部分主体构建器中添加具有指定类型的所有请求参数,如下面的一个图像文件。我已经设置了媒体类型解析multipart/form-data以及我设置媒体类型解析text/plain的其他一些参数。这个构建器将构建为生成Multipart Body,并且可以通过在多部分体中使用body注释来发送。

&#13;
&#13;
@Multipart
@POST("user/update")
Call<ResponseBody> addDocument(@@Part MultipartBody file);


final MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
      .setType(MultipartBody.FORM);

requestBodyBuilder.addFormDataPart("doc_image_file", imageFile.getName(),
      RequestBody.create(MediaType.parse("multipart/form-data"), imageFile));
requestBodyBuilder.addFormDataPart("user_id", null, RequestBody.create(MediaType.parse("text/plain"),"12"));
requestBodyBuilder.addFormDataPart("doc_name", null, RequestBody.create(MediaType.parse("text/plain"),"myfile"));
requestBodyBuilder.addFormDataPart("doc_category", null, RequestBody.create(MediaType.parse("text/plain"),category));
requestBodyBuilder.addFormDataPart("doc_image_file", imageFile.getName(),RequestBody.create(MediaType.parse("multipart/form-data"),imageFile));
requestBodyBuilder.addFormDataPart("doc_text_content", null, RequestBody.create(MediaType.parse("text/plain"),body));
RequestBody multipartBody = requestBodyBuilder.build();
&#13;
&#13;
&#13;

答案 3 :(得分:1)

您还可以使用Map RequestBody作为值,将字符串作为键添加参数,然后使用Multipart和PartMap发送。

检查以下代码,希望它会有所帮助:

@Multipart
@POST("/add")
Call<ResponseBody> addDocument(@PartMap Map<String,RequestBody> params);

Map<String, RequestBody> map = new HashMap<>();

map.put("user_id", RequestBody.create(MediaType.parse("multipart/form-data"), SessionManager.getInstance().getCurrentUserId()));
map.put("doc_name", RequestBody.create(MediaType.parse("multipart/form-data"), CommonUtils.removeExtension(textFile.getName())));
map.put("doc_category", RequestBody.create(MediaType.parse("multipart/form-data"), category));
map.put("doc_image_file", RequestBody.create(MediaType.parse("multipart/form-data"), imageFile));
map.put("doc_text_content", RequestBody.create(MediaType.parse("multipart/form-data"), body));
map.put("doc_update_time", RequestBody.create(MediaType.parse("multipart/form-data"), "" + new Date(textFile.lastModified())));

答案 4 :(得分:0)

只需按照网络浏览器进行多部分操作即可。他们将嵌套的密钥放在“[]”中,并为图像提供密钥。

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

然后在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);

答案 5 :(得分:0)

Here is my json request format is :
{
"task":{
"category_id":"1",
"price":"10",
"description":"1",
"task_videos_attributes":[
{
"link":"video file goes here",
"size":"100x100"
}
]
}
}



// my request becomes 
 HashMap<String, RequestBody> task = new HashMap();          
  task.put("task[category_id]", createPartFromString(categoryId));
  task.put("task[price]", createPartFromString("" + etPrice.getText().toString()));
            task.put("task[description]", createPartFromString("" + etDescription.getText().toString()));


// for videos file list
  final List<MultipartBody.Part> body = new ArrayList<>();
  for (int i = 0; i < videos.size(); i++) {

 task.put("task[task_videos_attributes][" + i+ "][size]", createPartFromString("100x100"));

 File videoFile = new File(videos.get(i));
                        RequestBody requestBody = RequestBody.create(MediaType.parse("video/mp4"), videoFile);
                        MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("task[task_videos_attributes][" + i + "][link]", videoFile.getName(), requestBody);
                        body.add(fileToUpload);

}


// here is a final call
  new RestClient(this).getInstance().get().postTask(body, task).enqueue(callback);




// This function converts my string to request body
   @NonNull
    private RequestBody createPartFromString(String descriptionString) {
        if (descriptionString == null)
            return RequestBody.create(MultipartBody.FORM, "");
        return RequestBody.create(
                MultipartBody.FORM, descriptionString);

    }

希望这可以帮助你...

答案 6 :(得分:0)

https://www.linkedin.com/pulse/retrofit-2-how-upload-multiple-files-server-mahesh-gawale

我想可以在这里找到这个问题的最佳答案。对我来说效果很好。

这是在Android中使用翻新功能上传文件数组的示例。

这是服务的外观 公共接口ApiService {

@POST("/event/store")
Call<ResModel> event_store(@Body RequestBody file);

} 这是Client类的样子 公共类ApiClient {     公共静态最终字符串API_BASE_URL =“ api基本网址”;

private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(API_BASE_URL).addConverterFactory(GsonConverterFactory.create());

public static ApiService createService(Class<ApiService> serviceClass)
{
    Retrofit retrofit = builder.client(httpClient.build()).build();
    return retrofit.create(serviceClass);
}

} 在活动或片段或您想要的位置上传这样的视频     ApiService服务= ApiClient.createService(ApiService.class);

MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);


builder.addFormDataPart("event_name", "xyz");
builder.addFormDataPart("desc", "Lorem ipsum");

// Single Image
builder.addFormDataPart("files",file1.getName(),RequestBody.create(MediaType.parse("image/*"), file1));

// Multiple Images 
for (int i = 0; i <filePaths.size() ; i++) {
        File file = new File(filePaths.get(i));
        RequestBody requestImage = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        builder.addFormDataPart("event_images[]", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
        }


MultipartBody requestBody = builder.build();
Call<ResModel> call = service.event_store(requestBody);
call.enqueue(new Callback<ResponseBody>() {
     @Override
     public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
         Toast.makeText(getBaseContext(),"All fine",Toast.LENGTH_SHORT).show();
     }

     @Override
     public void onFailure(Call<ResponseBody> call, Throwable t) {
        Toast.makeText(getBaseContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
     }
 });

注意:filePaths.size()是拾取图像路径的Arraylist。 希望这篇文章对您有用。请在此处分享您的反馈作为评论。

答案 7 :(得分:0)

这对我有用。

我所做的是使用

添加其他所有参数
MultipartBody.Part Partname = MultipartBody.Part.createFormData("ParamName", "Value");

也许您不需要创建其他主体,而只需添加文件或发送对象之外的其他参数。最后在界面上,我将所需的每个身体部位作为参数。

@Multipart
@POST("api/service/uploadVideo")
Call<ResponseBody> uploadVideoToServer(
        @Part MultipartBody.Part video,
        @Part MultipartBody.Part param2,
        @Part MultipartBody.Part param3 ....
);