文件上传无法使用Retrofit

时间:2015-11-30 20:47:04

标签: android retrofit okhttp

我以前使用apache来预先形成文件上传:

FileBody fileBody = new FileBody(new File(path), mimeType);
FormBodyPart formBodyPart = new FormBodyPart("partName", fileBody);

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart(formBodyPart);

...

这将成功上传部件名称为“partName”

的文件

切换到改装:

public interface UploadService {
    @Multipart
    @PUT("/somepath/{id}/upload")
    Call<ResponseBody> upload(@Path("id") String id, @Part("partName") RequestBody file);
}

var id = 123;
UploadService service = retrofit.create(UploadService.class);
File file = new File(path);
RequestBody requestBody = RequestBody.create(MediaType.parse(mimeType), file);

Response<ResponseBody> response = service.upload(id, requestBody).execute();

未设置请求的partName。我做错了什么?

1 个答案:

答案 0 :(得分:0)

我的代码上传文件,改编如下: 用api:

@Multipart
@POST("url")
Call<Response> uploadImage(@Path("id") long id, @Part("file\"; filename=\"image.jpg") RequestBody file);

改装请求:

Retrofit retrofit = new Retrofit.Builder().baseUrl(URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
ApiClass apiClass = retrofit.create(ApiClass.class);
RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), imageFile);
Call<Response> call = apiClass.uploadImage(id, requestBody);

希望它对你有所帮助,祝你好运!