You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Alamofire上传多图(multipart表单)遇prescription字段必填错误

Fix for "The prescription field is required" in Alamofire Multipart Upload

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 guard statements to handle cases where UIImageJPEGRepresentation returns 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 just prescription for 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:49:26