Sending Custom Object as form-data in Alamofire

Viewed 30

I have an endpoint in Java to upload a file on my server. It accepts MultipartFile and an Info object in form-data.

@PostMapping(path = "/mobile/upload", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE})
public HttpEntity<String> fileUpload(@RequestPart Info fileInfo, @RequestPart MultipartFile file, @RequestHeader("x-auth") String token){}

Using Alamofire my first approach was this but I was getting 415 error, probably because the way I was sending fileInfo was not correct. I made sure of this by commenting the Info object from server side and then tried sending the file alone and it was a success.

func uploadDocument(fileUrl: URL, fileInfo: Info, authKey: String) {
    let headers: HTTPHeaders = [ "x-auth": authKey ]
    AF.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(fileUrl, withName: "file")
        multipartFormData.append(fileInfo, withName: "fileInfo")
    }, to: "my_url", method: .post,headers: headers)
    .responseDecodable(of: UploadResponse.self) { response in }
}

Then I tried encoding my fileInfo object, again 415 error code.

let jsonObj = (try? JSONEncoder().encode(fileInfo))!
//
multipartFormData.append(jsonObj, withName: "fileInfo")

Also tried but getting exception 'NSInvalidArgumentException'

multipartFormData.append(((fileInfo as AnyObject).data(using: String.Encoding.utf8.rawValue))!, withName: "fileInfo")

How can I send this object in Alamofire ?

I am able to perform the request in Postman with 200. enter image description here

0 Answers
Related