【问题标题】:Rails paperclip gem with Android Retrofit 2.X not working带有Android Retrofit 2.X的Rails回形针宝石不起作用
【发布时间】:2023-03-10 21:15:01
【问题描述】:

我正在创建 Rails 后端以使用回形针 gem 从浏览器和移动客户端 (Android) 上传图像。它适用于所有 Web 浏览器、移动浏览器以及 HTTP REST 客户端工具,但不适用于带有改造 http 库的 android 客户端。这是相互兼容的吗

【问题讨论】:

    标签: android ruby-on-rails-4 paperclip retrofit2


    【解决方案1】:

    答案是肯定的 让它工作并不容易,但是,

    我是这样做的……它对我有用

    接口声明

    public interface MultimediaApi {
    
    @Multipart
    @POST("api/v1/multimedia")
    Call<ResponseBody> uploadMultimedia(@Part("tipo]") String tipo,
                                   @Part("archivo\"; filename=\"myimageName\" ") RequestBody archivo, // archivo is the how we named the field of the file in rails server
    // see filename=\"myimageName\" does not have file extension to avoid problems with paperclip content types validations
                                   @Part("texto") String texto,
                                   @Part("acoplable_id") String acoplable_id,
                                   @Part("acoplable_type") String acoplable_type
                                  );
    }
    

    在执行线程上

    Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RestConnection.BASE_URL_MULTIMEDIA)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
    
        MultimediaApi apiService =
                retrofit.create(MultimediaApi.class);
    
        Call<ResponseBody> call;
        MediaType MEDIA_TYPE = MediaType.parse("image/jpeg");
        File file = new File(filePath);
        RequestBody requestBody = RequestBody.create(MEDIA_TYPE, file);
    
        call = apiService.uploadMultimedia(
                            type.toString(),
                            requestBody,
                            text.toString(),
                            acopable_id.toString(),
                            acopable_type.toString()
                    );
    
        Response<ResponseBody> response = call.execute();
    
    
            int statusCode = response.code();
            if (statusCode == 201) {
                // Server response OK            
            } else {
               //failed
                    Throwable th = new Throwable("Status Code:" + statusCode + " Error uploading image... Response: " + response.body());
                    return th;
                }
    

    这个例子对我帮助很大,为了解决我的问题,我只是做了一些改变让它工作,所以要小心查看每个细节

    https://guides.codepath.com/android/Consuming-APIs-with-Retrofit

    https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server

    /**Pura Vida**/
    

    【讨论】:

    • 谢谢.. 这很有帮助.. 我缺少请求的文件名属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    相关资源
    最近更新 更多