我正在尝试使用Alamofire将图像与其他帖子参数一起上传。
查看我看到的文档:
Alamofire.upload(
.POST,
"https://httpbin.org/post",
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn")
multipartFormData.appendBodyPart(fileURL: rainbowImageURL, name: "rainbow")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
}
case .Failure(let encodingError):
print(encodingError)
}
}
)
但我怎样才能上传一系列图片,如:
var arrayOfImages: [UIImage] = [some images...]
与其他帖子数据一起:
let parameters: [String: AnyObject] = [
"id": id,
"title": title,
"desc": description,
"images[]": arrayOfImages
]
答案 0 :(得分:2)
func uploadProfileGIF(imageArray: NSMutableArray){
var count = 0
let bucketname = DAO.getBucketNameForLoggedInUser()
let uploadUrl = "https://whatever.com/whatever"
for i in imageArray{
var objectname = "picture" + String(count)
let image = i;
//Turn image into data
let imageData: NSData = UIImagePNGRepresentation(image as! UIImage)!
let params = ["objectname" : objectname, "bucketname" : bucketname!, "isGifImgae" : "True", "content_type" : "image/jpeg"]
let manager = AFHTTPSessionManager()
manager.POST(uploadUrl, parameters: params, constructingBodyWithBlock: { (AFMultipartFormData) in
AFMultipartFormData.appendPartWithFileData(imageData, name: "file", fileName: "image", mimeType: "image/jpeg")
}, progress: nil, success: { (s:NSURLSessionDataTask, response) in
print(response)
}) { (s:NSURLSessionDataTask?, e:NSError?) in
print(e)
}
count+=1
}
}
这就是我这样做的方式。希望这可以帮助。它的AlamoFire,它是一个POST请求,我想是一个不同的语法。只是一个for循环,它为数组中的每个图像进行API调用。
编辑:
因此,不要使用for循环并单独调用API五次,只需更改AFMultipartofrmdata的名称即可。当您访问文件时,传入5个文件然后在您的API中,只需按名称访问它们。例如,我的API抓取文件的方式就是这样的
data = self.request.get('file')
现在数据是我的图像,我可以这样上传。 只需在同一API调用中执行五次不同的操作即可。
AFMultipartFormData.appendPartWithFileData(imageData1, name: "file1", fileName: "image", mimeType: "image/jpeg")
AFMultipartFormData.appendPartWithFileData(imageData2, name: "file2", fileName: "image", mimeType: "image/jpeg")
AFMultipartFormData.appendPartWithFileData(imageData3, name: "file3", fileName: "image", mimeType: "image/jpeg")
AFMultipartFormData.appendPartWithFileData(imageData4, name: "file4", fileName: "image", mimeType: "image/jpeg")
AFMultipartFormData.appendPartWithFileData(imageData5, name: "file5", fileName: "image", mimeType: "image/jpeg")
然后只需在for循环中指定名称和NSData。
然后在API方面,有类似的东西;
image1 = self.request.get('file1')
image2 = self.request.get('file2')
image3 = self.request.get('file3')
image4 = self.request.get('file4')
image5 = self.request.get('file5')
希望这有帮助!这就是我改变了我的API调用,而不是为每个用户调用5次不同的时间。