如何在上传MultipartFormData时在参数中添加struct:
let parameters = [
"parameter1": "test1",
"parameter2": "test2"]
Alamofire.upload(multipartFormData: { multipartFormData in
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
multipartFormData.append(structObject, withName: "user")
if let imageData = UIImageJPEGRepresentation(image, 1) {
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "file.png", mimeType: "image/png")
}
}, to: url, encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if let value = response.result.value as AnyObject?{
let json = JSON(value)
} else {
}
}
case .failure(let encodingError):
print(encodingError)
}
}
)
我可以毫无问题地添加额外的参数,但我无法将参数添加到参数数组
谢谢
答案 0 :(得分:1)
在multipartFormData下面添加以下内容以在参数map之间循环并附加参数键和值:
let parameters = [
"parameter1": "test1",
"parameter2": "test2"]
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(structObject, withName: "user")
if let imageData = UIImageJPEGRepresentation(image, 1) {
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "file.png", mimeType: "image/png")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}
}, to: url, encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if let value = response.result.value as AnyObject?{
let json = JSON(value)
} else {
}
}
case .failure(let encodingError):
print(encodingError)
}
}
)