我想在
Android中将二进制文件上传到服务器.我通过邮递员测试Api方法:
没关系,你可以看到还有另一个选项可以上传文件作为表单数据(键,值):
每个教程(如this one)都描述了如何将文件作为multipart / form-data上传:
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("picture", file.getName(), requestFile);
我搜索了很多,但找不到任何方法上传文件作为二进制与retrofit2.
API服务:
@POST("trip/{tripId}/media/photos")
Call postEventPhoto(
@Path("eventId") int tripId,
@Header("Authorization") String accessToken,
@Query("direction") String direction,
@Body RequestBody photo);
呼叫者:
InputStream in = new FileInputStream(new File(media.getPath()));
byte[] buf;
buf = new byte[in.available()];
while (in.read(buf) != -1);
RequestBody requestBody = RequestBody
.create(MediaType.parse("application/octet-stream"), buf);
Call mediaPostCall = tripApiService.postTripPhoto(
tripId,
((GlobalInfo) getApplicationContext()).getApiAccessToken(),
direction,
requestBody);
但我得到了这个错误:
java.lang.IllegalArgumentException: @Body parameters cannot be used with form or multi-part encoding.
我的代码出了什么问题?我该怎么办?