web-dev-qa-db-fra.com

Téléchargez des fichiers avec des paramètres de multipartformdata en utilisant alamofire 5 dans ios swift

J'essaie de télécharger des fichiers avec des paramètres (multipartformdata) mais je ne peux pas le faire avec la nouvelle version Alamofire 5, si vous avez une certaine expérience avec Alamofire 5, partagez-la avec moi.

 func uploadPluckImage(imgData : Data, imageColumnName : String,  url:String,httpmethod:HTTPMethod,completionHandler: @escaping (NSDictionary?, String?) -> ()){
    let token = UserDefaults.standard.string(forKey: PrefKeys.loginToken) ?? ""
    let authorization = ["Authorization" : "Bearer \(token)"]
    let parameters: Parameters?
    parameters = [
        "garbageCollector": 0,
        "stuff_uuid": "2b4b750a-f4a6-4d61-84ce-7c42b5c030ee",
        "delete_file" : ""
    ]
    let headers : HTTPHeader?
    headers = ["Authorization" : "Bearer \(token)"]
    let imageURl = "http://68.183.152.132/api/v1/stuff/uploader"


    AF.upload(multipartFormData: { (multipart: MultipartFormData) in
        let imageData = self.firstImage.image?.jpegData(compressionQuality: 0.7)
            multipart.append(imageData, withName: "file", fileName: "file.png", mimeType: "image/png")

        for (ker, value) in parameters!{
            multipart.append(value as! String).data(using: .utf8)!, withName: key)
        }
    },usingThreshold: UInt64.init(),
       to: imageURl,
       method: .post,
       headers: headers,
       encodingCompletion: { (result) in
        switch result {
        case .success(let upload, _, _):
            upload.uploadProgress(closure: { (progress) in
              print("Uploading")
            })
            break
        case .failure(let encodingError):
            print("err is \(encodingError)")
                break
            }
        })
}
11
Diaa SAlAm

Vous pouvez le faire en utilisant Router URLRequestConvertible

static func performMultiPartFile<T:Decodable>(imageData: Data, route:APIRoute,decoder: JSONDecoder = JSONDecoder(), completion: @escaping (_ result: T?, _ error: String?) -> ()) {
    Alamofire.upload(multipartFormData: { (multipartFormData) in
        multipartFormData.append(imageData, withName: "image", fileName: "iosImage.jpg", mimeType: "image/jpg")
    }, with: route) { (encodingResult) in
        switch encodingResult {

        case .success(let upload, _, _):
            upload.responseString { (response) in
                if response.result.isSuccess {
                    if let JSON = response.result.value {

                        debugPrint("✅ Respons Object >>>> " + String(describing: JSON))
                        do {
                            let result = try JSONDecoder().decode(T.self, from: JSON.data(using: .utf8)!)
                            debugPrint("✍️ Result: " + String(describing: result))
                            completion(result, nil)
                        } catch let error { // mapping fail
                            debugPrint("❌ Error in Mapping" + String(describing: error))
                            completion(nil, String(describing: error))
                        }
                    }
                } else {
                    debugPrint("❌ ???? Response fail : \(response.result.description)")
                    completion(nil, (response.result.error?.localizedDescription)!)
                }
            }
        case .failure(let encodingError):
            completion(nil, String(describing: encodingError))
        }

    }
}
0
Bola Ibrahim

Voici comment je télécharge des images et des vidéos à partir d'une application Swift 5 avec Alamofire 5.

Images

    /**
     Send Image to server
     */

    func Post(imageOrVideo : UIImage?){  

    let headers: HTTPHeaders = [
        /* "Authorization": "your_access_token",  in case you need authorization header */
        "Content-type": "multipart/form-data"
    ]


        AF.upload(
            multipartFormData: { multipartFormData in
                multipartFormData.append(imageOrVideo!.jpegData(compressionQuality: 0.5)!, withName: "upload_data" , fileName: "file.jpeg", mimeType: "image/jpeg")
        },
            to: "http://ip.here.--.--/new.php", method: .post , headers: headers)
            .response { resp in
                print(resp)               

        }
}

Vous pouvez créer une ressource temporaire et utiliser l'url temporaire (bon pour les vidéos):

/**
 Send video to server
 */
func PostVideoUrl(url : URL){

    let headers: HTTPHeaders = [
        "Content-type": "multipart/form-data"
    ]        

    AF.upload(
        multipartFormData: { multipartFormData in
            multipartFormData.append(url, withName: "upload_data" , fileName: "movie.mp4", mimeType: "video/mp4")
    },
        to: "http://ip.here.--.--/newVideo.php", method: .post , headers: headers)
        .response { resp in
            print(resp)

    }

}
0
Boris Detry