【问题标题】:Upload list of objects to mysql using Retrofit Android使用 Retrofit Android 将对象列表上传到 mysql
【发布时间】:2018-02-10 10:33:38
【问题描述】:

我有一个自定义对象的 ArrayList,每个对象都有大约 10 个字段,我已经设法将其上传到我们的服务器。问题是其中一个字段是一个字符串,其中包含我从文件转换的 Base64 编码字符串,Retrofit Gson 创建者似乎不喜欢它。这个问题可以通过只发送所有没有图像的字段来解决,然后使用 ftp 上传所有图像,但如果我能以某种方式将图像放入对象中会容易得多。

问题:如何使用 Retrofit 将 Base64 编码的字符串作为自定义对象内的字段发送到 url?

【问题讨论】:

  • 当您尝试使用 Gson 创建对象时出现什么问题?

标签: android json base64 retrofit retrofit2


【解决方案1】:
@FormUrlEncoded
@POST("/UploadImages")
Call<ResponseBody> postImages(@Body ArrayListImage img);

//POJO CLASS

public class ArrayListImage {
    @SerializedName("image")
    @Expose
    private ArrayList<String> image;
    public ArrayListImage(ArrayList<String> image) {
        this.image=image;
    }
}

【讨论】:

    【解决方案2】:

    下面是我使用Retrofit上传文件的RequestBody代码:

    RequestBody lRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
    MultipartBody.Part lFile = MultipartBody.Part.createFormData("file", file.getName(), lRequestBody);
    MultipartBody.Part title = MultipartBody.Part.createFormData("title", file.getName());
    MultipartBody.Part lFilenamebase64 = MultipartBody.Part.createFormData("filenamebase64", base64EncodedFileName);
    

    对文件名进行编码:

    String base64EncodedFileName = Base64.encodeToString(file.getName().getBytes(Charsets.UTF_8), Base64.URL_SAFE | Base64.NO_WRAP);
    

    我将 api 定义为:

    @Multipart
    @POST("/upload") 
    Observable<Response<ResponseBody>> uploadFile(@Part MultipartBody.Part file, @Part MultipartBody.Part title, @Part MultipartBody.Part base64EncodedFileName);
    

    希望对你有帮助。

    【讨论】:

      【解决方案3】:
      //Convert Object list into json string. 
      
      Gson gson = new Gson();
      String objListString = gson.toJson(objectList);
      
      @FormUrlEncoded
      @POST("********")
      Call<JsonObject> sendObjectList(@Field("objListString") String objListString);
      
        And at the web end parse string into json.
        @enjoy
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-29
        • 1970-01-01
        • 2021-05-11
        • 2020-07-17
        • 2017-06-07
        • 1970-01-01
        • 2021-11-04
        • 2021-03-18
        相关资源
        最近更新 更多