使用 Alamofire 上传具有 base64String 编码的多个图像的数组
Posted
技术标签:
【中文标题】使用 Alamofire 上传具有 base64String 编码的多个图像的数组【英文标题】:Upload Array having base64String encoded multiple images using Alamofire 【发布时间】:2016-04-04 07:14:46 【问题描述】:我正在努力使用 Alamofire 将多个图像发送到后端。我在 NSMutableArray 中添加了 base64 图像字符串。现在我正在尝试将这个字符串数组发送到服务器,但它不起作用。
我尝试过通过这种方式上传单张图片,效果非常棒,但为什么不是一组图片。
图像选择 -
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage
imageView.contentMode = .ScaleAspectFit
imageView.image = pickedImage
slctdImage = pickedImage
dismissViewControllerAnimated(true, completion: nil)
uploadImage(slctdImage)
上传中
func uploadImage( image:UIImage)
let pic :NSData = UIImageJPEGRepresentation(image, 0.5)!
let str = pic.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
//imageArray is declared as var imageArray = NSMutableArray()
imageArray.addObject(str)
//when imageArray count reaches 3 I send the images
if imageArray.count==3
let parameters = [
"task": "doNotification",
"image" : imageArray,
"select_category" : "exams",
"select_type" : "quarterly",
"class" : "1",
"repliable" : "0",
"select_students" : ["25","26"],
"select_group" : "Super Users",
"title" : "Hello",
"text" : "asdfsdf",
"date" : "2015-12-15",
"time" : "10:50 AM"]
Alamofire.request(.POST, UrlClass.baseUrl, parameters:parameters ) .response
(request, response, data, error) in
// self.startParsing(data!)
print(response)
那么如何解决这个问题呢?请建议修改代码或其他方式。
【问题讨论】:
您确定您调用的端点支持一次发送多个图像吗?如果是这样,我会假设它需要将它们作为 MultipartFormData 发送。 【参考方案1】:使用以下代码将图像上传到服务器
let image = UIImage(named:"testImage")
Alamofire.upload(
.POST,
URL,
multipartFormData: multipartFormData in
multipartFormData.appendBodyPart(data: UIImageJPEGRepresentation(image, 1)!, name: "imageFile",
fileName: "image.jpg", mimeType: "image/jpeg")
,
encodingCompletion: encodingResult in
switch encodingResult
case .Success(let upload, _, _):
upload.progress bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
dispatch_async(dispatch_get_main_queue())
let percent = (Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))
//progress(percent: percent)
print(percent)
upload.validate()
upload.responseJSON response in
if response.result.error != nil
// failure
else
// success
case .Failure(let encodingError):
print(encodingError)
//failure
)
多张图片
Alamofire.upload(
.POST,
urlString,
multipartFormData: multipartFormData in
multipartFormData.appendBodyPart(data: "122222".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"Id")
multipartFormData.appendBodyPart(data: "test1111".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"sId")
multipartFormData.appendBodyPart(data: "", name :"ContractorIds")
multipartFormData.appendBodyPart(data:date.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"ExpectedOn")
multipartFormData.appendBodyPart(data:date.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"ExpiresOn")
multipartFormData.appendBodyPart(data: data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"Notes")
for image in images
if let imageData = UIImageJPEGRepresentation(image, 0.05)
multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "file.jpeg", mimeType: "image/jpeg")
,
【讨论】:
您可以通过追加到multipartFromData数组来发送参数 以及您能否提及任何用于多张图片上传的代码。 是否需要在后端写一些特殊的编码。 兄弟什么是失败?它写了使用未解决的标识符“失败”。 不需要Abhishek,请检查上面编辑的多个图像上传到服务器的答案,您也可以在将参数附加到多部分数据时指定编码类型。【参考方案2】:这是另一个版本,因为我在服务器端遇到了读取多个图像的问题:
Alamofire.upload(multipartFormData: (multipartFormData) in
// Sending parametes with images
multipartFormData.append(jsonString.data(using: String.Encoding.utf8)!, withName: "parameters")
for (key, value) in parameters
if let files = value as? Array<Any>, key == "files"
for i in files.enumerated()
let image = UIImage(named: "\(i.element)")
// add image
multipartFormData.append(UIImageJPEGRepresentation(image!, 1)!, withName: "file" , fileName: "\( NSUUID().uuidString)" , mimeType: "image/jpeg")
// if you face problem add below lines as to make sepration between two images
multipartFormData.append("\r\r".data(using: String.Encoding.utf8)!, withName: "")
else
,to:baseURL)
【讨论】:
以上是关于使用 Alamofire 上传具有 base64String 编码的多个图像的数组的主要内容,如果未能解决你的问题,请参考以下文章
使用 Alamofire 将图像作为 base64String 上传
如何使用 Alamofire 上传具有身份验证的 MultipartFormData