我正在尝试访问REST API,它允许我上传不同数量的文件,具体取决于具体情况。我已经为Alamofire获得了以下代码,但我不知道如何更改它以便我可以上传一个文件,两个文件或十个文件。
Alamofire.upload(
.POST,
"https://httpbin.org/post",
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(fileURL: farmFileURL, name: "xml-file-farm")
multipartFormData.appendBodyPart(fileURL: farmFileURL, name: "csv-measurement-file-1")
multipartFormData.appendBodyPart(fileURL: farmFileURL, name: "csv-measurement-file-2")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
我看到的问题是我无法使用'multipartFormData'定义文件数组,因为在你进入'upload'方法之前它不存在。
答案 0 :(得分:2)
创建一个包含fileName
及其URL
的元组数组并简单地传递它:
func uploadFiles(files:[(String,NSURL)]){
Alamofire.upload(
.POST,
"https://httpbin.org/post",
multipartFormData: { multipartFormData in
for (fileName, fileURL) in files{
multipartFormData.appendBodyPart(fileURL: fileURL, name: fileName)
}
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
}