0

I was previously using apache to preform file upload:

FileBody fileBody = new FileBody(new File(path), mimeType); FormBodyPart formBodyPart = new FormBodyPart("partName", fileBody); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart(formBodyPart); ... 

That would successfully upload the file with the part name of 'partName'

Switching to retrofit:

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(); 

The partName of the request is not set. What am I doing wrong?

4
  • 1
    My answer at stackoverflow.com/questions/33932916/… using OkHttp, however, IMO, perhaps its logic can help you little Commented Dec 1, 2015 at 1:22
  • Awesome thanks. I can try a track down what is wrong with retrofit. And worst case just use okhttp as a work around. Commented Dec 1, 2015 at 1:52
  • IMO, you can check at Headers.of("Content-Disposition", "form-data; name=\"file\"; filename=\"ic_launcher.png\"") because with my web service (Asp.Net Web API), when android client did not set filename here, the web service did not think it is a multipart request Commented Dec 1, 2015 at 2:02
  • Apparantly file uploads are not working properly with PUT requests. Changing to POST should probably make it work. I'm currently investigating a similar issue. Commented May 20, 2016 at 9:02

1 Answer 1

0

My code to upload file with retrofit below: With api:

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

Retrofit request:

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); 

Hope it help you, good luck!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.