Reputation: 946
I want to upload file with JSON object. I am using retrofit2, but I get 400 Bad request. My request example using curl:
curl -X POST http://localhost:8082/attachment -F filename=37.pdf -F 'data={"DocumentTypeID":2, "DocumentID":1, "Description":"описание","AttachmentTypeId":2}'
Also I made request in postman and it also works:
My Java Code:
Uri path = Uri.fromFile(file);
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getMimeType(path)),
file
);
MultipartBody.Part body =
MultipartBody.Part.createFormData("filename", file.getName(), requestFile);
FileDescriptionObject fdo = new FileDescriptionObject();
fdo.setDescription("test");
fdo.setDocumentId(fileModel.Id);
fdo.setDocumentTypeId(1);
fdo.setAttachmentTypeId(2);
Gson gson = new Gson();
String ds1 = gson.toJson(fdo);
RequestBody description =
RequestBody.create(
MediaType.parse("text/plain"), ds1);
Call<ResponseBody> call = activity.getAsyncHelper().getWebService().postFile(
"http://localhost:8082/attachment",
body,
description);
My API:
@Multipart
@POST
Call<ResponseBody> postFile(@Url String url,
@Part MultipartBody.Part file,
@Part("data")RequestBody data);
My logs:
D/OkHttp: --> POST http://localhost:8082/attachment
Content-Type: multipart/form-data; boundary=520da8f2-5fac-4567-be0f-61618cc881bd
D/OkHttp: Content-Length: 468
D/OkHttp: --520da8f2-5fac-4567-be0f-61618cc881bd
D/OkHttp: Content-Disposition: form-data; name="filename"; filename="4.pdf"
Content-Type: application/pdf
Content-Length: 3
323
--520da8f2-5fac-4567-be0f-61618cc881bd
Content-Disposition: form-data; name="data"
Content-Transfer-Encoding: binary
Content-Type: text/plain; charset=utf-8
Content-Length: 77
{"AttachmentTypeId":2,"Description":"test","DocumentId":4,"DocumentTypeId":1}
--520da8f2-5fac-4567-be0f-61618cc881bd--
--> END POST (468-byte body)
Maybe the problem is in this additional headers from json data? I think so because in postman they are not added.
Upvotes: 2
Views: 3901
Reputation: 12463
Change
RequestBody description = RequestBody.create(MediaType.parse("text/plain"), ds1);
to
MultipartBody.Part description = MultipartBody.Part.createFormData("data", ds1);
and see if that works. Also change you API call to
@Multipart
@POST
Call<ResponseBody> postFile(@Url String url,
@Part MultipartBody.Part file,
@Part MultipartBody.Part data);
Upvotes: 7