Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 如何使用Alamofire上载阵列或文件(图像)列表_Swift_Alamofire_Multipartform Data - Fatal编程技术网

Swift 如何使用Alamofire上载阵列或文件(图像)列表

Swift 如何使用Alamofire上载阵列或文件(图像)列表,swift,alamofire,multipartform-data,Swift,Alamofire,Multipartform Data,我正在使用以下代码将图像上载到服务器,它工作正常,但我需要根据一个参数(即“hunter_pictures”)上载一个数组或图像列表 尝试以下方法: func uploadImages(pictures: [UIImage]) { let url = "your url" let headers: HTTPHeaders = [Keys.authorization: "your token"] Alamofire.upload(multipartFormData: {

我正在使用以下代码将图像上载到服务器,它工作正常,但我需要根据一个参数(即“hunter_pictures”)上载一个数组或图像列表

尝试以下方法:

func uploadImages(pictures: [UIImage]) {

    let url = "your url"
    let headers: HTTPHeaders = [Keys.authorization: "your token"]

    Alamofire.upload(multipartFormData: { (multipartFormData) in

        for image in pictures {
            if let imageData = UIImageJPEGRepresentation(image, 1) {
                multipartFormData.append(imageData, withName: "pictures[\(index)]", fileName: "picture", mimeType: "image/jpeg")
            }
        }

    }, to: url, method: .post, headers: headers) { (encodingResult) in

        switch encodingResult {

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

                let json = response.result.value
                print(json)
            }

        case .failure(let encodingError):
            print(encodingError.localizedDescription)
        }
    }
}
尝试以下方法:

func uploadImages(pictures: [UIImage]) {

    let url = "your url"
    let headers: HTTPHeaders = [Keys.authorization: "your token"]

    Alamofire.upload(multipartFormData: { (multipartFormData) in

        for image in pictures {
            if let imageData = UIImageJPEGRepresentation(image, 1) {
                multipartFormData.append(imageData, withName: "pictures[\(index)]", fileName: "picture", mimeType: "image/jpeg")
            }
        }

    }, to: url, method: .post, headers: headers) { (encodingResult) in

        switch encodingResult {

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

                let json = response.result.value
                print(json)
            }

        case .failure(let encodingError):
            print(encodingError.localizedDescription)
        }
    }
}

集成多个图像上传的步骤:

func callAPIForImagesUpload(images: [UIImage],
                            parameters:[String: String]?,
                            success:@escaping ((_ response: Any?) -> Void),
                            failure:@escaping ((_ error: Error?) -> Void)) {
    let apiURL = "xyz/"
    let requestHeaders: HTTPHeaders = ["Authorization": "token value"]
    let fileName = "user" // This will be the parameter name in which server is expecting the image data

    Alamofire.upload(multipartFormData: { multipartFormData in

        for i in 0..<images.count {
            if let imageData = UIImageJPEGRepresentation(images[i], 1) {
                multipartFormData.append(imageData, withName: "image_" + "\(i)", fileName: fileName, mimeType: "image/jpeg")
            }
        }

        // Append parametrs too, if any
        let params = parameters ?? [String: String]()
        for (key, value) in params {
            // Appending parameters in the request
            multipartFormData.append((value.data(using: .utf8))!, withName: key)
        }

    }, to: apiURL, method: .post, headers: requestHeaders) { encodingResult in

        switch encodingResult {
        case .success(let upload, _, _):
            // Check whether status code lie between `200-300` range; mostly it would be `200`
            upload.validate(statusCode: 200..<300).responseJSON(completionHandler: { receivedInfo in
                print("Success: \(receivedInfo.result.value ?? "error occurred in response value")")
                success(receivedInfo.result.value)
            })
        case .failure(let error):
            print("Error: \(error.localizedDescription)")
            failure(error)
        }
    }
}
  • 将图像数组和参数作为函数参数发送,包括成功和失败闭包

  • 将图像和参数附加到
    multipartFormData

  • 在相应的关闭中返回
    成功
    /
    失败

  • 代码片段:

    func callAPIForImagesUpload(images: [UIImage],
                                parameters:[String: String]?,
                                success:@escaping ((_ response: Any?) -> Void),
                                failure:@escaping ((_ error: Error?) -> Void)) {
        let apiURL = "xyz/"
        let requestHeaders: HTTPHeaders = ["Authorization": "token value"]
        let fileName = "user" // This will be the parameter name in which server is expecting the image data
    
        Alamofire.upload(multipartFormData: { multipartFormData in
    
            for i in 0..<images.count {
                if let imageData = UIImageJPEGRepresentation(images[i], 1) {
                    multipartFormData.append(imageData, withName: "image_" + "\(i)", fileName: fileName, mimeType: "image/jpeg")
                }
            }
    
            // Append parametrs too, if any
            let params = parameters ?? [String: String]()
            for (key, value) in params {
                // Appending parameters in the request
                multipartFormData.append((value.data(using: .utf8))!, withName: key)
            }
    
        }, to: apiURL, method: .post, headers: requestHeaders) { encodingResult in
    
            switch encodingResult {
            case .success(let upload, _, _):
                // Check whether status code lie between `200-300` range; mostly it would be `200`
                upload.validate(statusCode: 200..<300).responseJSON(completionHandler: { receivedInfo in
                    print("Success: \(receivedInfo.result.value ?? "error occurred in response value")")
                    success(receivedInfo.result.value)
                })
            case .failure(let error):
                print("Error: \(error.localizedDescription)")
                failure(error)
            }
        }
    }
    
    func callAPIForImagesUpload(图像:[UIImage],
    参数:[字符串:字符串]?,
    成功:@escaping((uu响应:Any?->Void),
    失败:@转义((\uError:error?->Void)){
    让apiURL=“xyz/”
    let requestHeaders:HTTPHeaders=[“授权”:“令牌值”]
    让fileName=“user”//这将是服务器需要图像数据的参数名
    上传(multipartFormData:{multipartFormData-in-in
    
    对于0中的i..集成多个图像上载的步骤:

    func callAPIForImagesUpload(images: [UIImage],
                                parameters:[String: String]?,
                                success:@escaping ((_ response: Any?) -> Void),
                                failure:@escaping ((_ error: Error?) -> Void)) {
        let apiURL = "xyz/"
        let requestHeaders: HTTPHeaders = ["Authorization": "token value"]
        let fileName = "user" // This will be the parameter name in which server is expecting the image data
    
        Alamofire.upload(multipartFormData: { multipartFormData in
    
            for i in 0..<images.count {
                if let imageData = UIImageJPEGRepresentation(images[i], 1) {
                    multipartFormData.append(imageData, withName: "image_" + "\(i)", fileName: fileName, mimeType: "image/jpeg")
                }
            }
    
            // Append parametrs too, if any
            let params = parameters ?? [String: String]()
            for (key, value) in params {
                // Appending parameters in the request
                multipartFormData.append((value.data(using: .utf8))!, withName: key)
            }
    
        }, to: apiURL, method: .post, headers: requestHeaders) { encodingResult in
    
            switch encodingResult {
            case .success(let upload, _, _):
                // Check whether status code lie between `200-300` range; mostly it would be `200`
                upload.validate(statusCode: 200..<300).responseJSON(completionHandler: { receivedInfo in
                    print("Success: \(receivedInfo.result.value ?? "error occurred in response value")")
                    success(receivedInfo.result.value)
                })
            case .failure(let error):
                print("Error: \(error.localizedDescription)")
                failure(error)
            }
        }
    }
    
  • 将图像数组和参数作为函数参数发送,包括成功和失败闭包

  • 将图像和参数附加到
    multipartFormData

  • 在相应的关闭中返回
    成功
    /
    失败

  • 代码片段:

    func callAPIForImagesUpload(images: [UIImage],
                                parameters:[String: String]?,
                                success:@escaping ((_ response: Any?) -> Void),
                                failure:@escaping ((_ error: Error?) -> Void)) {
        let apiURL = "xyz/"
        let requestHeaders: HTTPHeaders = ["Authorization": "token value"]
        let fileName = "user" // This will be the parameter name in which server is expecting the image data
    
        Alamofire.upload(multipartFormData: { multipartFormData in
    
            for i in 0..<images.count {
                if let imageData = UIImageJPEGRepresentation(images[i], 1) {
                    multipartFormData.append(imageData, withName: "image_" + "\(i)", fileName: fileName, mimeType: "image/jpeg")
                }
            }
    
            // Append parametrs too, if any
            let params = parameters ?? [String: String]()
            for (key, value) in params {
                // Appending parameters in the request
                multipartFormData.append((value.data(using: .utf8))!, withName: key)
            }
    
        }, to: apiURL, method: .post, headers: requestHeaders) { encodingResult in
    
            switch encodingResult {
            case .success(let upload, _, _):
                // Check whether status code lie between `200-300` range; mostly it would be `200`
                upload.validate(statusCode: 200..<300).responseJSON(completionHandler: { receivedInfo in
                    print("Success: \(receivedInfo.result.value ?? "error occurred in response value")")
                    success(receivedInfo.result.value)
                })
            case .failure(let error):
                print("Error: \(error.localizedDescription)")
                failure(error)
            }
        }
    }
    
    func callAPIForImagesUpload(图像:[UIImage],
    参数:[字符串:字符串]?,
    成功:@escaping((uu响应:Any?->Void),
    失败:@转义((\uError:error?->Void)){
    让apiURL=“xyz/”
    let requestHeaders:HTTPHeaders=[“授权”:“令牌值”]
    让fileName=“user”//这将是服务器需要图像数据的参数名
    上传(multipartFormData:{multipartFormData-in-in
    
    对于0中的我,..@maxwel的答案只做了一次修改,只需在文件名“hunter_picture.jpg”中添加文件格式。添加了.jpg,就成功了

    Alamofire.upload(
        multipartFormData: { multipartFormData in
        multipartFormData.append((userId.data(using: String.Encoding.utf8, allowLossyConversion: false))!, withName: "userID")
    
           for (index,image) in self.spottingImages.enumerated() {
              if let imageData = UIImageJPEGRepresentation(image, 1) {
                multipartFormData.append(imageData, withName: "hunter_picture[\(index)]", fileName: "hunter_picture.jpg", mimeType: "image/jpeg")  }
                                        }
        },
                    to: url,
                    encodingCompletion: { encodingResult in
                        switch encodingResult {
                        case .success(let upload, _, _):
                            print(upload)
                        case .failure(let encodingError):
                            print(encodingError)}
                })
    

    @maxwel的答案只做了一次修改,在文件名“hunter_picture.jpg”中添加了文件格式

    Alamofire.upload(
        multipartFormData: { multipartFormData in
        multipartFormData.append((userId.data(using: String.Encoding.utf8, allowLossyConversion: false))!, withName: "userID")
    
           for (index,image) in self.spottingImages.enumerated() {
              if let imageData = UIImageJPEGRepresentation(image, 1) {
                multipartFormData.append(imageData, withName: "hunter_picture[\(index)]", fileName: "hunter_picture.jpg", mimeType: "image/jpeg")  }
                                        }
        },
                    to: url,
                    encodingCompletion: { encodingResult in
                        switch encodingResult {
                        case .success(let upload, _, _):
                            print(upload)
                        case .failure(let encodingError):
                            print(encodingError)}
                })
    

    对于未来读取器的UIImageJPEGresentation已被实例方法UIImage.jpegData(压缩质量:)'替换为未来读取器的UIImageJPEGresentation已被实例方法UIImage.jpegData(压缩质量:)'