Reputation: 335
I'm trying to upload a file in swiftUI, using multipart form-data The code is like this:
do {
let data = try Data(contentsOf: url)
AF.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(data, withName: "uploadedFile",fileName: "uploadedFile",mimeType: "text/plain")
}, to: "https://server.com/upload",headers: ["Authorization" : "Bearer \(API.shared.accessToken!)",
"Content-Type": "multipart/form-data"])
.responseDecodable(of: String.self ) { response in
debugPrint(response)
}
}
catch {
print("Error \(error)")
}
Where url is a local URL, DocumentPickerViewController has provided.
For some reason the server gives an error saying something went wrong. This is the response I picked up in Charles:
And this the response I picked up in Postman (which works):
I noticed that postman automatically generated the Content type parameter in the formdata (which was an image in this test, but it could be any file type). Alamofire didn't do that by default, so I added filename and the mimetype (text/plain) in the request, but that didn't work.
Any thoughts? It works on Postman. So is this a server issue or a frontend issue?
Upvotes: 0
Views: 779
Reputation: 1794
This code worked for me , for uploading an image file
I used "application/x-www-form-urlencoded"
instead of "Content-Type": "multipart/form-data"
let url = "url here"
let headers: HTTPHeaders = [
"Authorization": "Bearer Token Here",
"Accept": "application/x-www-form-urlencoded"
]
AF.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData, withName: "image" ,fileName: "image.png" , mimeType: "image/png")
}, to: url, method: .post ,headers: headers).validate(statusCode: 200..<300).response { }
Upvotes: 1