[英]Upload data key in alamofire and URLSession, how to add it?
我需要將數據上傳到服務器,並且有此功能
uploadTask(with request: URLRequest, from bodyData: Data) -> URLSessionUploadTask
alamofire使用的簽名幾乎相同
upload(_ data: Data, with urlRequest: URLRequestConvertible)
任何想法如何添加名稱作為附加數據的鍵?
我看過這個iOS-如何使用uploadTask上傳視頻? 在標頭中添加文件名,我已經檢查過蘋果文檔,但沒有說明
非常感謝
假設您要上傳一個名為userImage
鍵的圖像,則可以使用Alamofire
多部分功能。 我在這里使用了SwiftyJSON
。 您可以根據自己的要求進行修改。
var parameters: [String:Any]?
//fill your parameters with data. Image is stored as Data and other values are string in this case.
Alamofire.upload(multipartFormData: { (multipartFormData:MultipartFormData) in
for (key, value) in parameters! {
if key == "userImage" {
multipartFormData.append(
value as! Data,
withName: key,
fileName: "profileImage.jpg",
mimeType: "image/jpg"
)
} else {
//multipartFormData
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
}
}
}, usingThreshold: 1, to: "yourServiceURL", method: .post, headers: ["yourHeaderkey":"value"]) { (encodingResult:SessionManager.MultipartFormDataEncodingResult) in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if response.result.error != nil {
return
}
if let data = response.result.value {
let json = JSON(data)
}
}
break
case .failure(let encodingError):
debugPrint(encodingError)
break
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.