我正在创建rails后端来从浏览器上传图像&使用paperclip gem的移动客户端(Android)。它适用于所有Web浏览器,移动浏览器和HTTP REST客户端工具,但不能与具有改造http库的Android客户端一起使用。这是否相互兼容
答案 0 :(得分:2)
答案是肯定的 不容易使它有效,但是,
我是怎么做到的......它为我工作
接口声明
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**/