使用Alamofire上传具有base64String编码多个图像的阵列

时间:2016-04-04 07:14:47

标签: ios swift uiimage alamofire

我正在努力使用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)


        }
    }

    }

那么如何解决这个问题呢?请建议修改代码或其他一些方法。

2 个答案:

答案 0 :(得分:2)

使用以下代码将图像上传到服务器

   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")
                    }
                }
            },

答案 1 :(得分:0)

这是另一个版本,因为我在服务器端面临读取多个图像的问题:

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)