我正在开发一个 Android 应用程序,它通过 Retrofit 向服务器 (rails) 发送请求。
我当前的问题是文件上传。在服务器端,我有回形针来处理文件上传。
我似乎无法在我想作为参数发送的对象中包含 TypedFile 这是我调用的 api 方法及其参数
@Multipart
@POST("/containers/{id}/items")
void addItem(@Path("id") int id,
@Part("item")NewItemData newItemData,
Callback<String> callback);
基本上我想发布这个对象(包含一个TypedFile
)
public class NewItemData{
String original_filename;
String content_type;
TypedFile file;
String description;
String location;
int container_id;
...
}
编辑: 我忘了向您展示如何创建该对象
public NewItemData(Context context, String file_path){
String mime_type = FileUtilities.getMimeType(file_path);
String[] file_name_parts = file_path.split("/");
String file_name = file_name_parts[file_name_parts.length-1];
this.original_filename = file_name;
this.full_file_path = file_path;
this.content_type = mime_type;
File file_tmp = new File(file_path);
this.file = new TypedFile("application/octet-stream", file_tmp);
this.description = "";
this.location = "";
}
结束编辑
这是我收到的错误:
retrofit.RetrofitError: retrofit.converter.ConversionException: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 2
这是 NewItemData 转换为 json 的对象
{"original_filename":"IMG_20150121_221732.jpg","content_type":"image/jpeg","description":"","file":{},"location":"","container_id":0}
正如您所看到的“file”字段为空,因此我假设上面的错误是指“file”=> {} 而不是二进制文件这一事实
到目前为止我所尝试的方法都没有奏效,所以我的问题是:
- 可以在多部分模式下发布“包装器”对象吗?
- 如果是这样,我应该写什么注释以及在哪里?
- 我应该实现自定义序列化器吗?
如果您需要更多信息,请询问 谢谢
最佳答案
当您创建restAdapter实例时,只需添加此行即可添加转换器.addConverterFactory( GsonConverterFactory.create()),如下所示
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(RestConnection.BASE_URL_MULTIMEDIA)
.addConverterFactory( GsonConverterFactory.create())
.client(client)
.build();
关于android - 在 Android 上使用 Retrofit 实现对象内部的 TypedFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28176588/