I am trying to upload multiple images to server via MultipartFormData
I had read many links, but couldn't solve mine. Code is working when we are uploading single file either .jpg or .png.
In Postman
multiple images are uploaded successfully.
Core Logic
let boundaryPrefix = "--\(boundary)\r\n"
body.append("\(boundaryPrefix)".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"\"; filename=\"\(listOfFiles[0].name)\"\r\n".data(using: .utf8)!)
body.append("Content-Type: image/png\r\n\r\n".data(using: .utf8)!)
body.append(convertFileToData(url: listOfFiles[0].pathURL)!)
body.append("\r\n".data(using: .utf8)!)
body.append("\(boundaryPrefix)".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"\"; filename=\"\(listOfFiles[1].name)\"\r\n".data(using: .utf8)!)
body.append("Content-Type: image/jpg\r\n\r\n".data(using: .utf8)!)
body.append(convertFileToData(url: listOfFiles[1].pathURL)!)
body.append("\r\n".data(using: .utf8)!)
body.append("--".appending(boundary.appending("--")).data(using: .utf8)!)
func convertFileToData(url: URL) -> Data? {
do {
let fileData = try Data(contentsOf: url)
return fileData
} catch {
return nil
}
}
session.dataTask(with: urlRequest) { (dataa, response, error) in
if error == nil {
if let _ = dataa {
do {
let val = try JSONDecoder().decode(UploadResponse.self, from: dataa!)
} catch {
}
} else { }
} else { }
}.resume()
Issues:
- Only first array of
Image
is reaching server. - Second image is not reaching server.
What mistake have I made?