web-dev-qa-db-fra.com

Téléchargez plusieurs images dans Swift utilisant Alamofire

J'utilise le code suivant pour télécharger une seule image sur un serveur:

private static func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, String>, imageData:NSData?, imageName: String) -> (URLRequestConvertible , NSData) {

    // create url request to send
    let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
    mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
    let boundaryConstant = "myRandomBoundary12345";
    let contentType = "multipart/form-data;boundary="+boundaryConstant
    mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")


    // create upload data to send
    let uploadData = NSMutableData()
    if(imageData != nil && imageData?.length != 0) {
        // add image
        uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Disposition: form-data; name=\"\(imageName)\"; filename=\"\(StringHelper.sharedInstance.randomString(5)).png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData(imageData!)
    }
    // add parameters
    for (key, value) in parameters {
        uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
    }
    uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    print("upload",parameters)
    // return URLRequestConvertible and NSData
    return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
}

Comment puis-je télécharger plusieurs images en un seul paramètre en modifiant ce code?

14
Arun sharma

Swift Utilisez simplement "[]" avec le paramètre de téléchargement d'image pour en faire un tableau d'images.

Alamofire.upload(multipartFormData: { multipartFormData in
            // import image to request
            for imageData in imagesData {
                multipartFormData.append(imageData, withName: "\(imageParamName)[]", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")
            }
            for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }
        }, to: urlString,

            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in

                    }
                case .failure(let error):
                    print(error)
                }

        })
34
Gurjit Singh

Celui-ci m'aide:

private func urlRequestWithComponentsForUploadMultipleImages(urlString:String, parameters:Dictionary<String, String>, imagesData:[Data], imageName: String) -> (URLRequestConvertible , Data) {

    // create url request to send
    var mutableURLRequest = URLRequest(url: NSURL(string: urlString)! as URL)

    mutableURLRequest.httpMethod = Alamofire.HTTPMethod.post.rawValue
    let boundaryConstant = "myRandomBoundary12345";
    let contentType = "multipart/form-data;boundary="+boundaryConstant
    mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")


    // create upload data to send
    var uploadData = Data()
    // add image
    for data in imagesData {
        uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
        uploadData.append("Content-Disposition: form-data; name=\"\(imageName)\"; filename=\"\(Date().timeIntervalSince1970).jpeg\"\r\n".data(using: String.Encoding.utf8)!)
        uploadData.append("Content-Type: image/jpeg\r\n\r\n".data(using: String.Encoding.utf8)!)
        uploadData.append(data)
    }
    // add parameters
    for (key, value) in parameters {
        uploadData.append("\r\n--\(boundaryConstant)\r\n".data(using: String.Encoding.utf8)!)
        uploadData.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".data(using: String.Encoding.utf8)!)
    }
    uploadData.append("\r\n--\(boundaryConstant)--\r\n".data(using: String.Encoding.utf8)!)
    print("upload",parameters)
    return (mutableURLRequest , uploadData)
}
4
Arun sharma

Il semble que cette question ait déjà été répondue sur SO, probablement à plusieurs endroits. Voici un lien que j'ai trouvé:

Comment télécharger plusieurs images en plusieurs parties en utilisant Alamofire?

Je vais coller leur solution pour plus de commodité, mais ils ont dit que cela fonctionne pour Swift 3.x:

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

La solution semble être basée sur l'approche recommandée détaillée dans la documentation d'Alamofire ici: https://github.com/Alamofire/Alamofire#uploading-multipartformdata

Alamofire.upload(
multipartFormData: { multipartFormData in
    multipartFormData.append(unicornImageURL, withName: "Unicorn")
    multipartFormData.append(rainbowImageURL, withName: "Rainbow")
},
to: "https://httpbin.org/post",
encodingCompletion: { encodingResult in
    switch encodingResult {
    case .success(let upload, _, _):
        upload.responseJSON { response in
            debugPrint(response)
        }
    case .failure(let encodingError):
        print(encodingError)
    }
})
2
Lobsterman

voici ma solution et cela fonctionnera à 100% sans bugs ..

        Alamofire.upload(multipartFormData: { (multipartFormData : MultipartFormData) in

            let count = imageToUpload.count

            for i in 0..<count{
                multipartFormData.append(imageToUpload[i], withName: "morephoto[\(i)]", fileName: "photo\(i).jpeg" , mimeType: "image/jpeg")

            }
            for (key, value) in parameterrs {

                    multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
            }
            print(multipartFormData)
        }, to: url!) { (result) in

                switch result {
                case .success(let upload, _ , _):

                    upload.uploadProgress(closure: { (progress) in

                        print("uploding: \(progress.fractionCompleted)")
                    })

                    upload.responseJSON { response in

                    print(response.result.value!)
                    let resp = response.result.value! as! NSDictionary
                    if resp["status"] as! String == "success"{
                        print(response.result.value!)
                        let alert = UIAlertController(title: "Alert", message: "Image Upload Successful", preferredStyle: UIAlertControllerStyle.alert)
                        alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil))
                        self.present(alert, animated: true, completion: nil)


                    }
                    else{

                    }


                }

            case .failure(let encodingError):
                print("failed")
                print(encodingError)

            }
        }

en cela, le tableau imagetoupload est le tableau de données d'image que j'ai fait auparavant.

1
ap00724