如何使用 alamofire 上传多个文件并显示进度?
Posted
技术标签:
【中文标题】如何使用 alamofire 上传多个文件并显示进度?【英文标题】:How to upload multiple file using alamofire with showing progress? 【发布时间】:2016-11-15 10:15:51 【问题描述】:我想将多个文件上传到 ios 中的服务器。我有数据作为 NSData,我想将它上传到服务器。我正在使用 alamofire 上传数据。我浏览了他们的文档,但找不到好的答案。我无法理解下面的代码将如何处理 NSData 和多个图像。请提供解决方案。
let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")
Alamofire.upload(fileURL, to: "https://httpbin.org/post")
.uploadProgress progress in // main queue by default
print("Upload Progress: \(progress.fractionCompleted)")
.downloadProgress progress in // main queue by default
print("Download Progress: \(progress.fractionCompleted)")
.responseJSON response in
debugPrint(response)
【问题讨论】:
【参考方案1】:使用以下代码使用 Alamofire 上传多张图片。你可以找到它周围的文档here: -
Alamofire.upload(
multipartFormData: multipartFormData in
multipartFormData.append(data, name: "imageFile",
fileName: "image.jpg", mimeType: "image/jpeg"),
multipartFormData.append(data1, name: "image1File",
fileName: "image1.jpg", mimeType: "image/jpeg")
,
to: "https://httpbin.org/post", //URL,
headers: headers,
encodingCompletion: encodingResult in
switch encodingResult
case .success(let upload, _, _):
upload.responseJSON response in
debugPrint(response)
upload.uploadProgress(closure: //Get Progress
progress in
print(progress.fractionCompleted)
)
case .failure(let encodingError):
print(encodingError)
)
注意:这是使用 Alamofre 4.0
【讨论】:
您的代码有错误。尽管您改进了代码。 请随意编辑和改进答案。 @deepakkumar 上传过程中如何在uitableviewcell中显示进度条?【参考方案2】:对于多张图片上传,进度 ios swift
Alamofire.upload(multipartFormData: multipartFormData in
multipartFormData.append(data, withName: "file", fileName: "image.jpg", mimeType:"image/jpeg")
multipartFormData.append(data1, withName: "file", fileName: "image1.jpg", mimeType:"image/jpeg")
,
to: url, method: .post, headers: headers) (result) in
switch result
case .success(let upload, _, _):
upload.uploadProgress(closure: (progress) in
let progressVal = String(format: "%.2f%%", progress.fractionCompleted * 100)
print("\(progressVal)")
)
upload.responseJSON response in
print(response)
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
【讨论】:
以上是关于如何使用 alamofire 上传多个文件并显示进度?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 alamofire 将多个 PDF 文件上传到服务器? #Swift 4 #IOS [重复]