我一直在网上思考如何使用Alamofire
上传图像,并得到了这个结果。我能够实现此解决方案,该解决方案从API收到200响应,但实际上并没有上传图像。似乎我要附加图像,但请求正文为nil。
[更具体地说,当我将图像Data
附加到multiFormData
时,我附加了图像,但请求的body
为nil
时发生了问题。因此,响应是成功的,但是API没有接收到图像,而是接收到具有零个图像的请求。
func upload(briefId: String,
curationId: String,
media: [Any]?,
progressCompletion: @escaping (_ percent: Float) -> Void,
completion: @escaping (_ mediaArray: [Media]) -> Void) {
guard let media = media else {
return
}
Alamofire.upload(multipartFormData: { multipartFormData in
media.forEach { item in
if item is UIImage {
if let imageData = (item as? UIImage), let imgData = imageData.jpegData(compressionQuality: 0.5) {
let format = imgData.format
let uuid = UUID().uuidString
multipartFormData.append(imgData,
withName: "media",
fileName: "\(uuid).\(format)",
mimeType: "image/jpeg")
}
}
}
},
with: MediaUploadRouter.upload(briefId: briefId, curationId: curationId),
encodingCompletion: { encodingResult in
print(encodingResult)
switch encodingResult {
case .success(let upload, _, _):
upload.uploadProgress { progress in
progressCompletion(Float(progress.fractionCompleted))
}
upload.validate()
upload.responseJSON { response in
print(response)
//3
completion([])
}
case .failure(let encodingError):
print(encodingError)
}
})
}
正如我之前说过的,实际上我从200
得到了API
代码,但是API
没有收到任何图像。
▿ [Request]: POST https://api/id123/curation/id789/media
[Timeline]: Timeline: { "Request Start Time": 613650563.882, "Initial Response Time": 613650579.293, "Request Completed Time": 613650579.298, "Serialization Completed Time": 613650579.298, "Latency": 15.412 secs, "Request Duration": 15.416 secs, "Serialization Duration": 0.000 secs, "Total Duration": 15.416 secs }
▿ request : Optional<URLRequest>
▿ some : https://api/id123/curation/id789/media
▿ url : Optional<URL>
▿ some : https://api/id123/curation/id789/media
- _url : https://api/id123/curation/id789/media
- cachePolicy : 0
- timeoutInterval : 10000.0
- mainDocumentURL : nil
- networkServiceType : __C.NSURLRequestNetworkServiceType
- allowsCellularAccess : true
▿ httpMethod : Optional<String>
- some : "POST"
▿ allHTTPHeaderFields : Optional<Dictionary<String, String>>
▿ some : 2 elements
▿ 0 : 2 elements
- key : "Content-Type"
- value : "multipart/form-data; boundary=alamofire.boundary.fd461e96ba613621"
▿ 1 : 2 elements
- key : "Authorization"
- value : "Bearer tokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentokentoken-g”
▿ httpBody : Optional<Data>
▿ some : 0 bytes
- count : 0
▿ pointer : 0x00007ffee83a0860
- pointerValue : 140732794538080
- bytes : 0 elements
- httpBodyStream : nil
- httpShouldHandleCookies : true
- httpShouldUsePipelining : false
▿ response : Optional<NSHTTPURLResponse>
- some : <NSHTTPURLResponse: 0x600000248da0> { URL: https://api/id123/curation/id789/media } { Status Code: 200, Headers {
"Content-Type" = (
"application/json; charset=utf-8"
);
Date = (
"Fri, 12 Jun 2020 10:29:38 GMT"
);
Server = (
Kestrel
);
"Transfer-Encoding" = (
Identity
);
} }
问题似乎出在media
类型的参数[Any]?
上。您确定要传递UIImage
参数中的media
吗?您可以通过提供其他条件来检查它:
if item is UIImage {
if let imageData = (item as? UIImage), let imgData = imageData.jpegData(compressionQuality: 0.5) {
let format = imgData.format
let uuid = UUID().uuidString
multipartFormData.append(imgData,
withName: "media",
fileName: "\(uuid).\(format)",
mimeType: "image/jpeg")
} else {
print("This was not an image.")
}
}