android - 在 Android 上使用 Retrofit 实现对象内部的 TypedFile

标签 android retrofit paperclip

我正在开发一个 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/

相关文章:

android - 如何使用我自己的键盘而不是默认键盘?

java - 如何使用retrofit解析json数组?

android - 改造:预期为 BEGIN_OBJECT 但为 BEGIN_ARRAY

android - 我无法保存关联模型 (ActiveAndroid)

ruby - 重命名模型后更新回形针文件名?

android - 如何使用 adb 命令在任何 android 上查找 CPU 温度

android - 错误 :Execution failed for task 'ndkBuild' . > 进程 'command ' Android\sdk\ndk-bundle/ndk-build.cmd'' 以非零退出值 2 完成

java - 使用本地 Sqlite 数据库开发简单的测验应用程序,但分数没有增加

ruby-on-rails - 如何在 Ruby on Rails 中使用回形针使模型具有无限图像?

ruby-on-rails - 回形针 gem 渲染头像在不同 View 中上传