我无法正确地访问提供给我的API以获取所需的响应。我已经使用Swift和Alamofire一段时间了,但这是我第一次使用multipart/form-data上传图像。我能够使用Postman上传图片,但我无法使用Alamofire框架发送相同的消息。
我的 Swift 代码:
func postFulfilWish(wish_id: Int, picture : UIImage, completionHandler: ((AnyObject?, ErrorType?) -> Void)) {
var urlPostFulfilWish = Constant.apiUrl;
urlPostFulfilWish += "/wishes/";
urlPostFulfilWish += String(wish_id);
urlPostFulfilWish += "/fulfill/images" ;
let image : NSData = UIImagePNGRepresentation(UIImage(named: "location.png")!)!
Alamofire.upload(.POST, urlPostFulfilWish, headers: Constant.headers, multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: image, name: "file")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
//This is where the code ends up now
//So it's able to encode my message into multipart/form-data but it's not doing it in the correct way for the API to handle it
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
}
fileName: "file.jpeg"1
这个参数对我很有帮助。在设置了除这个参数以外的所有内容后,一旦设置了这个参数,一切都正常工作了!谢谢! - Muhammad Yusuf