我正在创建 rails 后端以使用回形针 gem 从浏览器和移动客户端(Android)上传图像。它适用于所有 Web 浏览器、移动浏览器以及 HTTP REST 客户端工具,但不适用于带有改造 http 库的 android 客户端。这是否相互兼容
问问题
335 次
1 回答
3
答案是肯定 的 让它发挥作用并不容易,但是,
这就是我的做法......它对我有用
接口声明
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**/
于 2016-01-03T07:30:01.057 回答