我有一个关于使用Alamofire将图像上传到API服务器的问题。
BaseURL:http://vietnamtravelguide-app.com/quangnam/api_inquangnam/tips/create?user_id=""& token ="" 3个参数:location_id,content,imageName
可以通过POSTMAN发布
我的代码:
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(image, withName: "imageName", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
}, with: path, encodingCompletion: {encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print(response.result)
switch response.result {
case .success:
let json = JSON(response.result.value!)
if(delegate != nil) {
delegate!.didReceiveResult(json,basePath: basePath)
}
case .failure(let error):
print(error)
} }
case .failure(let encodingError):
print(encodingError)
}
})
with image(来自参数转换的图像作为数据)。当我调试它时,我得到了response.result返回失败
答案 0 :(得分:4)
您没有上传其余两个参数content
和location_id
。
试试这个,看看结果。我在这里也使用了SwiftyJSON
。
这是我所有API处理的APIManager
类。
import Alamofire
import SwiftyJSON
class APIManager: NSObject {
class func apiMultipart(serviceName:String,parameters: [String:Any]?, completionHandler: @escaping (JSON?, NSError?) -> ()) {
Alamofire.upload(multipartFormData: { (multipartFormData:MultipartFormData) in
for (key, value) in parameters! {
if key == "imageName" {
multipartFormData.append(
value as! Data,
withName: key,
fileName: "swift_file.jpg",
mimeType: "image/jpg"
)
} else {
//Data other than image
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
}
}
}, usingThreshold: 1, to: serviceName, method: .post, headers: ["yourHeaderKey":"yourHeaderValue"]) { (encodingResult:SessionManager.MultipartFormDataEncodingResult) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if response.result.error != nil {
completionHandler(nil,response.result.error as NSError?)
return
}
print(response.result.value!)
if let data = response.result.value {
let json = JSON(data)
completionHandler(json,nil)
}
}
break
case .failure(let encodingError):
print(encodingError)
completionHandler(nil,encodingError as NSError?)
break
}
}
}
}
如果您没有任何标题,则可以将该字段设为["":""]
以代替["yourHeaderKey":"yourHeaderValue"]
现在为了打电话我刚刚在控制器中形成了参数。
var params = [String:AnyObject]()
params["content"] = "something" as AnyObject?
params["location_id"] = "201" as AnyObject?
// Grab your image from some variable or imageView. Here self.profileImage is a UIImage object
if let profileImageData = self.profileImage {
if let imageData = UIImageJPEGRepresentation(profileImageData, 0.5) {
params["imageName"] = imageData as AnyObject?
APIManager.apiMultipart(serviceName: "http://yourAPIURL", parameters: params, completionHandler: { (response:JSON?, error:NSError?) in
//Handle response
})
} else {
print("Image problem")
}
}