使用Alamofire上传多图(multipart表单)遇prescription字段必填错误
Hey, I see exactly what's causing your issue here! Let's break it down and fix it step by step.
The Core Problem
You've wrapped your image appending logic inside DispatchQueue.main.async—this is why your prescription[] images never make it to the backend.
Alamofire runs the multipartFormData closure immediately to assemble the form data before initiating the upload. When you use DispatchQueue.main.async, that code gets queued to run later on the main thread—long after the closure has finished executing and the form data has already been finalized. So your images are never actually added to the request!
Fixed Code
Here's the corrected version of your upload logic, with the async wrapper removed and some minor safety improvements:
let parameters = [ "address": self.addressField.text ?? "", "pharmacy_id": "\(pharmaID ?? 0)", "is_default": "\(isDefault ?? 0)", "cash_payment": "1", // No need for string interpolation here "is_home_delivery": "\(isDelivery ?? 0)" ] as [String : Any] Alamofire.upload(multipartFormData:{ multipartFormData in // Add all text parameters first for key in parameters.keys { guard let val = parameters[key] as? String else { continue } multipartFormData.append(val.data(using: .utf8)!, withName: key) } // Add images directly here—NO DispatchQueue.main.async! for image in self.presImagesArray { guard let imageData = UIImageJPEGRepresentation(image, 0.5) else { print("Failed to convert image to JPEG data") continue } multipartFormData.append(imageData, withName: "prescription[]", fileName: "image.jpeg", mimeType: "image/jpeg") } }, usingThreshold: UInt64(0), to: url, method: .post, headers: headers, encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in print(response) self.clearAllNotice() self.successNotice("Success") } case .failure(let encodingError): print(encodingError, encodingError.localizedDescription) self.clearAllNotice() self.errorNotice(encodingError.localizedDescription) } }) } else { self.noticeInfo("Login Needed") }
Additional Notes
- Safety Check: Added
guardstatements to handle cases whereUIImageJPEGRepresentationreturns nil (e.g., if an image is corrupted), preventing unexpected crashes. - Cleanup: Removed unnecessary string interpolation for
cash_payment—just use"1"directly. - Key Name: Double-check that your backend expects the image field to be named
prescription[](some APIs use justprescriptionfor multiple files, but your error message suggests[]is correct here).
This should resolve the "prescription field is required" error, as your images will now be included in the multipart form data when the request is sent.
内容的提问来源于stack exchange,提问作者Chaudhry Talha

