图像Multipart在类类型对象中.
案例1.(我做过的)
服务参数:
{"id":"1","name":"vishal","image/file":""}
那时我的改造API
@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,@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);
我不知道为什么,但它返回错误,如:
“@Body parameters cannot be used with form or multi-part encoding”
任何帮助,将不胜感激.
解决方法
简单来说,我这样做了:
我改变了tested
Call<Result> resultCall = service.uploadImage(body);
至
调用<结果> resultCall = service.uploadImage(body,result);结果是什么
我的API的Result.java类(Response):
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);
?>
希望它能帮到你.谢谢.