Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

ios - How to upload multiple images in multipart using Alamofire?

I am stuck in uploading multiple images in multipart using Alamofire. Can any one help me? Thanks in advance!!

For more details, I am using this code to create body part of images data:

func imageArrayToNSData(array: [UIImage],boundary:String) -> NSData {
    let body = NSMutableData()
    var i = 0;
    for image in array{
        let filename = "image(i).jpg"
        let data = UIImageJPEGRepresentation(image,0.8);
        let mimetype = "image/jpeg"
        let key = "product_images"
        body.appendData("--(boundary)
".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("--(boundary)
".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("Content-Disposition: form-data; name="(key)"; filename="(filename)"
".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("Content-Type: (mimetype)

".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData(data!)
        body.appendData("
".dataUsingEncoding(NSUTF8StringEncoding)!)
        i += 1
    }

    body.appendData("--(boundary)--
".dataUsingEncoding(NSUTF8StringEncoding)!)
    return body
}

to upload I am using :

        Alamofire.upload(.POST, EDIT_PRODUCT_URL, headers: ["Accept": "application/json","Content-Type":"application/json"], multipartFormData: { (formData) in

        if productImages.count>0{
            let boundary = generateBoundaryString()
            let imageData = CommonClass.imageArrayToNSData(productImages,boundary: boundary)
            formData.appendBodyPart(data: imageData, name: "product_images", mimeType: "image/jpeg")
        }

        for (key, value) in params {
            if value is [String]{
                let data = CommonClass.stringArrayToNSData(value as! [String])
                formData.appendBodyPart(data:data , name: key)
            }else if value is String{
                formData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
            }else if let v = value as? Bool{
                var bValue = v
                let d = NSData(bytes: &bValue, length: sizeof(Bool))
                formData.appendBodyPart(data: d, name: key)
            }
        }

    }) { (encodingResult) in
        switch encodingResult {
        case .Success(let upload, _, _):
            KVNProgress.showProgress(CGFloat(0), status:"0% Sent")
            upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
                // This closure is NOT called on the main queue for performance
                // reasons. To update your ui, dispatch to the main queue.
                dispatch_async(dispatch_get_main_queue()) {
                    let prg = Int((CGFloat(totalBytesWritten)*100)/CGFloat(totalBytesExpectedToWrite))
                    if prg == 100{
                        KVNProgress.showSuccessWithStatus("Created")
                    }
                    KVNProgress.updateStatus("(prg)% Sent")
                    KVNProgress.updateProgress(CGFloat(Float(prg)/100.0), animated: true)
                }
            }
            upload.responseJSON { response in
                CommonClass.hideLoader()
                switch response.result {
                case .Success:
                    if let value = response.result.value {
                        let json = JSON(value)
                        print_debug("edit Product JSON is
(json)");  
                        completionBlock(json)
                    }else{
                        completionBlock(nil)
                    }
                case .Failure(let error):
                    print_debug(error.description)
                    showErrorWithMessage("Oops! Couldn't connect to server!")
                    completionBlock(nil)
                }
            }

        case .Failure(let encodingError):
            print(encodingError)
        }
    }

Can any one please let me suggest the way to upload multiple files in multipart using Alamofire?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I Hope it will be helpful for you:

Using Swift 3x: (I have uploaded four Photos in this snippet)

 //MARK: - upload multiple photos

    func uploadImagesAndData(params:[String : AnyObject]?,image1: UIImage,image2: UIImage,image3: UIImage,image4: UIImage,headers : [String : String]?, completionHandler:@escaping CompletionHandler) -> Void {

        let imageData1 = UIImageJPEGRepresentation(image1, 0.5)!
        let imageData2 = UIImageJPEGRepresentation(image2, 0.5)!

        let imageData3 = UIImageJPEGRepresentation(image3, 0.5)!

        let imageData4 = UIImageJPEGRepresentation(image4, 0.5)!


        Alamofire.upload(multipartFormData: { multipartFormData in

                for (key, value) in params! {
                    if let data = value.data(using: String.Encoding.utf8.rawValue) {
                        multipartFormData.append(data, withName: key)
                    }
                }

                multipartFormData.append(imageData1, withName: "file", fileName: "image.jpg", mimeType: "image/jpeg")
                multipartFormData.append(imageData2, withName: "file", fileName: "image.jpg", mimeType: "image/jpeg")
                multipartFormData.append(imageData3, withName: "file", fileName: "image.jpg", mimeType: "image/jpeg")
                multipartFormData.append(imageData4, withName: "file", fileName: "image.jpg", mimeType: "image/jpeg")

        },
            to: K_BASEURL + K_API_LOGINDATA, encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload
                        .validate()
                        .responseJSON { response in
                            switch response.result {
                            case .success(let value):
                                print("responseObject: (value)")
                            case .failure(let responseError):
                                print("responseError: (responseError)")
                            }
                    }
                case .failure(let encodingError):
                    print("encodingError: (encodingError)")
                }
        })
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...