如何在Swift中上传多张图片

时间:2019-07-10 09:23:41

标签: ios swift alamofire

我正在尝试借助Alamofire在服务器上上传多张图像,并且为了选择多张图像,我使用了BSImagePicker吊舱。

我创建了两个用于存储多张图片的变量

//Mark:- storing multiple images
var SelectedAssets = [PHAsset]()
var PhotoArray = [UIImage]()

这是我编写的用于在按钮操作时打开BSImagePicker的代码。

@IBAction func browseButtonTapped(_ sender: UIButton) {

    let vc = BSImagePickerViewController()
    vc.maxNumberOfSelections = 3
    //display picture gallery
    self.bs_presentImagePickerController(vc, animated: true,
                                         select: { (asset: PHAsset) -> Void in

    }, deselect: { (asset: PHAsset) -> Void in
        // User deselected an assets.

    }, cancel: { (assets: [PHAsset]) -> Void in
        // User cancelled. And this where the assets currently selected.
    }, finish: { (assets: [PHAsset]) -> Void in
        // User finished with these assets
        for i in 0..<assets.count
        {
            self.SelectedAssets.append(assets[i])

        }

        self.convertAssetToImages()

    }, completion: nil)

}

以及用于将资产转换为图像的代码

func convertAssetToImages() -> Void {

    if SelectedAssets.count != 0{

        for i in 0..<SelectedAssets.count{

            let manager = PHImageManager.default()
            let option = PHImageRequestOptions()
            var thumbnail = UIImage()
            option.isSynchronous = true

            manager.requestImage(for: SelectedAssets[i], targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFill, options: option, resultHandler: {(result, info)->Void in
                thumbnail = result!
                self.PhotoArray.append(thumbnail) // here I stored it in photoArray
            })

        }
    }

}

现在这是上传多张图片的代码

 func uploadMultipleImagesToServer(postId: String) {

    print(userDetail.getUserID())
    let param: [String:Any] = ["user_id": String.getString(userDetail.getUserID()), "post_id": postId]
    var image = [UIImage()]
    image = self.PhotoArray

    print(image)

    Alamofire.upload(multipartFormData: { (multipartFormData) in

        image.indices.forEach {
            multipartFormData.append(image[$0].jpegData(compressionQuality:0.8)!, withName: "file[\($0)]", fileName: "swift_file\($0).jpeg", mimeType: "image/jpeg")
        }

        for (key, value) in param {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key)
        }
    }, to: Constants.BASE_URL+"upload_image.php")
    { (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                //Print progress
                print("uploading \(progress)")
            })
            upload.responseJSON { response in
                //print response.result
                guard let json = response.result.value as? [String:Any] else {return}
                print(json)
                guard let status = json["status"] as? String else {return}
                print(status)
                if status == "1" {
                    guard let message = json["message"] as? String else {return}
                    print(message)
                    //                        self.showNormalAlertWithTitle("Success", message: message)
                    self.navigationController?.popViewController(animated: true)
                } else if status == "0" {
                    guard let message = json["message"] as? String else {return}
                    print(message)
                    //    self.showNormalAlertWithTitle("Alert!", message: message)
                }
                else {
                }
            }
        case .failure( _): break
            //print encodingError.description
        }
    }
}

但这给了我

错误
  

上传有效图像。只能使用PNG和JPEG。

我不明白我在做什么错。请帮忙吗?

3 个答案:

答案 0 :(得分:1)

/**
 * @brief this is a generic method use to Post method API call uploading multiple images array with multipart
 * @param url : String
 * @param arrayImageData:NSMutableArray
 * @param imageParamKey:String
 * @param  parameters:Parameters
 * @param isHeaderIncluded : Bool
 * @param headers : HTTPHeaders
 * @return completion block which return data dictionary
 **/


public func RequestApiMultipleImages(url:String,imageParamKey:String, arrayImageData:NSMutableArray, parameters:Parameters,isHeaderIncluded:Bool, headers:HTTPHeaders, completion: @escaping (_ result: DataResponse<Any>) -> Void) {

   if(isHeaderIncluded) {
    Alamofire.upload(multipartFormData: { multipartFormData in
        // import image to request
        for imageData in arrayImageData {
            multipartFormData.append(imageData  as! Data, withName: imageParamKey+"[]", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")
        }

        for (key, value) in parameters {
            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }
   }, to:url,headers:headers)
   {
        (result) in
        switch result {
        case .success(let upload,_,_ ):
            upload.uploadProgress(closure: { (progress) in
                //Print progress
                print(progress) 
            })
            //To check and verify server error
            /*upload.responseString(completionHandler: { (response) in
             print(response)
             print (response.result)
             })*/
            upload.responseJSON
                { response in

                    switch response.result {
                    case .success:
                        print(response)
                        completion(response)
                        break
                    case .failure(let error):
                        print(error)
                        completion(response)
                 }  
            }

        case .failure(_):
            print(result)
            // completion(responds)
        }
    }
    }
    else
   {
    Alamofire.upload(multipartFormData: { multipartFormData in
        // import image to request
        for imageData in arrayImageData {
            multipartFormData.append(imageData  as! Data, withName: imageParamKey+"[]", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")
        }

        for (key, value) in parameters {
            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }
    }, to:url)
    {
        (result) in
        switch result {
        case .success(let upload,_,_ ):
            upload.uploadProgress(closure: { (progress) in
                //Print progress
                print(progress)  
            })
            //To check and verify server error
            /*upload.responseString(completionHandler: { (response) in
             print(response)
             print (response.result)
             })*/
            upload.responseJSON
                { response in

                    switch response.result {
                    case .success:
                        print(response)
                        completion(response)
                        break
                    case .failure(let error):
                        print(error)
                        completion(response)
                    }   
            }

        case .failure(_):
            print(result)
            // completion(responds)
        }
    }
    }
}

答案 1 :(得分:0)

在这里尝试使用此代码

func callPostApiMultipleImage(api:String, parameters:[String:AnyObject]?,arr_images:[UIImage],Name:String, mime_type:String = "image/jpg", File_name:String = "image_" + String(arc4random()) + ".jpg", complition:@escaping (AnyObject)->Void){

        Alamofire.upload(multipartFormData: { (multipartFormData) in

            for i in 0..<arr_images.count{
                multipartFormData.append(arr_images[i].jpegData(compressionQuality: 0.1)!, withName: Name + "\(i)", fileName: File_name, mimeType: mime_type)
            }

        }, to:api){ (result) in

            switch result {

            case .success(let upload, _, _):

                upload.uploadProgress(closure: { (progress) in
                    print(progress)
                })

                upload.responseJSON { response in

                    print(response.result)

                    do {

                        let jsonDict = try JSONSerialization.jsonObject(with: (response.data as Data?)!, options: []) as? [String:AnyObject]

                        if response.result.error != nil{

                            print(response.result.error as Any, terminator: "")

                        }

                        if jsonDict == nil

                        {
                            print("Whoops, Something went wrong. Please, try after sometime.")
                            return

                        }

                        print(jsonDict as Any, terminator: "")

                        if response.result.isSuccess

                        {
                            complition(jsonDict as AnyObject)
                        }

                    }catch let error as NSError {

                        print("json error: \(error.localizedDescription)")

                    } catch _ {

                        print("Exception!")
                        print("Whoops, Something went wrong. Please, try after sometime.")
                    }

                }

            case .failure(let encodingError):

                print("",encodingError.localizedDescription)
                break

            }
        }
    }

答案 2 :(得分:0)

您可以使用此块将多个图像存储在json上

        let bodyImages:NSMutableArray = NSMutableArray()
    for i in 0..<products.count
    {

        let base64String = products[i]
        //print(base64String)
        let dict:NSDictionary = ["customer_company_images" : base64String]
        bodyImages.add(dict)
        print(bodyImages)

    }