I'm trying to send file on server using Retrofit2. I do everything according documentation, but always get 400 server error.
I'm tried to do like this:
RequestBody body =
RequestBody.create(MediaType.parse("image/png"), photo);
//..........
@Multipart
@POST(ADD_PHOTO)
Observable<HPSPhotoResponse>
addPhoto(@Part("file") RequestBody file);
...and like this:
MultipartBody.Part part = MultipartBody.Part.createFormData("file", "file", body);
//...........
@Multipart
@POST(ADD_PHOTO)
Observable<HPSPhotoResponse>
addPhoto(@Part("file") MultipartBody.Part files);
does't matter. Result is always the same "Multipart request: Required MultipartFile parameter 'file' is not present" - server response.
I would think that Spring on the server works not good but I do the equivalent code on Swift (iOS) and it works! Here Server sees this 'file' part.
Alamofire.upload(method, endpoint, headers: headers,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(fileURL: self.filePath!, name: "file")
}
Now I want it works on Android with Retrofit. But I even look in logs of Retrofit requests and indeed I don't see any 'file' text in the logs.
What's wrong with that?
In my case server was not handling some headers which retrofit is sending. That's why I had to remove useless header from retrofit requests. I've created interface function like this:
And call it like:
see details here: Upload picture to server using retrofit 2
You can try the following sample code. In this demo app, we will upload a photo after selecting from the Gallery. Hope it helps!
build.gradle file:
WebAPIService.java file:
FileActivity.java file: