使用 Retrofit 2.0 上传文件

Upload file with Retrofit 2.0

我正在使用这种方法将文件上传到我的服务器:

@Multipart
@POST("new")
Call<Response> send(@Part("myFile") byte[] file);

我一直在阅读,有些人使用 TypedFile 来做到这一点,也许这比像我这样发送原始字节更容易。

TypedFile class 在 retrofit.mime 包中。但我那里没有。这个包从 2.0 版本中删除了吗?还是我必须添加另一个依赖项?如果有,是哪一个?

谢谢。

在 2.0 中,您需要使用 RequestBody 而不是 TypedFile。使用 RequestBody 获取文件

RequestBody file = RequestBody.create(MediaType.parse("image/*"), path);    

在您的请求中使用它

@Multipart
@POST("new")
Call<Response> send(@Part("myFile") RequestBody file);

更多信息https://github.com/square/retrofit/issues/1063