简体   繁体   English

如何使用Alamofire将多部分图像上传到服务器

[英]How to upload multipart image to server using Alamofire

Below mentioned is my method to upload a multipart image to the server but when I am trying to do so the app is crashing "unexpectedly found nill" 下面提到的是我将多部分图像上传到服务器的方法,但是当我尝试这样做时,应用程序崩溃了“意外地发现了nill”

But value of image is there as I am selecting it from photo library. 但是图像的价值在那里,因为我正在从照片库中选择它。

func createCoupon(_ code: String, storeID: Int, description: String, terms: String, image: UIImage, startDate: String, endDate: String, couponDiscount: String, minimumDiscount: String, percentage: String, maximumDiscount: String){
    let urlString = BaseURL + "create-coupon"
    let params =
        [
            "code"               :  code,
            "store_id"           :  storeID,
            "type"               :  "merchant",
            "description"        :  description,
            "terms"              :  terms,
            "start_date"         :  startDate,
            "end_date"           :  endDate,
            "coupon_discount"    :  couponDiscount,
            "minimum_total"      :  minimumDiscount,
            "percentage"         :  percentage,
            "maximum_discount"   :  maximumDiscount
            ] as [String : Any]

    let manager = Alamofire.SessionManager.default
    manager.session.configuration.timeoutIntervalForRequest = 30000
    Alamofire.upload(multipartFormData: { (multipartFormData) in
        multipartFormData.append(UIImageJPEGRepresentation(image, 0.2)!, withName: "image", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
        for (key, value) in params {
            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }
    }, to:urlString)
    {
        (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                //Print progress
            })
            upload.responseJSON { response in
                let resJson = response.result.value
                print(resJson)
                NotificationCenter.default.post(name: Notification.Name(rawValue: NotifRequestSuccess.createCoupon.rawValue), object: nil, userInfo: ["data": resJson!])
            }

        case .failure(let encodingError):
            NotificationCenter.default.post(name: Notification.Name(rawValue: NotifRequestError.createCoupon.rawValue), object: encodingError, userInfo: nil)
        }
    }
Alamofire.upload(multipartFormData: { (multipartFormData) in
            multipartFormData.append(UIImageJPEGRepresentation(self.photoImageView.image!, 0.5)!, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
            for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }
            }, to:"http://server1/upload_img.php")
        { (result) in
            switch result {
            case .success(let upload, _, _):

                upload.uploadProgress(closure: { (Progress) in
                    print("Upload Progress: \(Progress.fractionCompleted)")
                })

                upload.responseJSON { response in
                    //self.delegate?.showSuccessAlert()
                    print(response.request)  // original URL request
                    print(response.response) // URL response
                    print(response.data)     // server data
                    print(response.result)   // result of response serialization
                    //                        self.showSuccesAlert()
                    //self.removeImage("frame", fileExtension: "txt")
                    if let JSON = response.result.value {
                        print("JSON: \(JSON)")
                    }
                }

            case .failure(let encodingError):
                //self.delegate?.showFailAlert()
                print(encodingError)
            }

        }

Just simple Use this Function as 只是简单使用此功能为

/// Data for image
var userImageString = Data()

/// Convert Image to Data
func convertImageToData(image: UIImage) -> Data {            
     let imageData = UIImageJPEGRepresentation(image, 0.1)!
     return imageData
 }

 ///Conversion Method - with target size if required
 userImageString = convertImageToData(image: resizeImage(image: img, targetSize: CGSize.init(width: 600, height: 600)))

//MARK: Data to server
func imageDataToServer(parameters: [String : AnyObject])
{
    Alamofire.upload(multipartFormData: { (multipartFormData) in
        multipartFormData.append(self.userImageString, withName: "parameter_name", fileName: "image.jpeg", mimeType: "image/jpeg")
        for (key, value) in parameters
        {
            multipartFormData.append(value.data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }

    }, to:"url", method: .post,
                     encodingCompletion: { encodingResult in
                         switch encodingResult {
                         case .success(let upload,_,_):

                             upload.responseJSON { (response:DataResponse<Any>) in
                                 print("RRRRR: \(response)")
                                 if response.result.isSuccess
                                 {
                                     /// Success
                                 }
                                 else
                                 {
                                     /// Failure
                                 }
                             }
                             upload.uploadProgress(closure: {
                                 progress in
                                 print(progress.fractionCompleted)
                             })
                         case .failure(let encodingError):
                             print(encodingError)
                         }
                     })
}

Function Usage 功能用法

if you have parameters send Parameters else nil or [:] 如果有参数,则发送参数,否则为nil或[:]

self.imageDataToServer(parameters: parameters)

Use Below code for single Image Upload using Alamofire : Swift 3.0 使用以下代码使用Alamofire上传单个图片: Swift 3.0

var strImagePicked = [UIImage]() // declared as global variable ... this will be image picked from ImagePickerController

Below is the function used for uploading single image from ImagePickerController and call this method when you click button to upload Image 以下是用于从ImagePickerController上传单个图像并单击按钮以上传Image时调用此方法的函数

func imageuploadAPI(){

    let params =
    [
        "code"               :  code,
        "store_id"           :  storeID,
        "type"               :  "merchant",
        "description"        :  description,
        "terms"              :  terms,
        "start_date"         :  startDate,
        "end_date"           :  endDate,
        "coupon_discount"    :  couponDiscount,
        "minimum_total"      :  minimumDiscount,
        "percentage"         :  percentage,
        "maximum_discount"   :  maximumDiscount
        ] as [String : Any]

    Alamofire.upload(
        multipartFormData: { MultipartFormData in

            for (key, value) in params {
                MultipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
            }

            for element in 0..<self.strImagePicked.count {

                let singleImage : Data? = self.strImagePicked[element].lowestQualityJPEGNSData as Data?

                MultipartFormData.append(singleImage!, withName: "image", fileName: "swift_file.jpg", mimeType: "image/jpeg")

                //"image" is the parameter for image 
            }
    }, to: "your_URL") { (result) in

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

            upload.responseJSON { response in
                print(response.result.value as Any)

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

// extension is used for image so that if image will be of hight quality it will reduce it's size
extension UIImage {

var highestQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 1.0)! as NSData }
var highQualityJPEGNSData: NSData    { return UIImageJPEGRepresentation(self, 0.75)! as NSData}
var mediumQualityJPEGNSData: NSData  { return UIImageJPEGRepresentation(self, 0.5)! as NSData }
var lowQualityJPEGNSData: NSData     { return UIImageJPEGRepresentation(self, 0.25)! as NSData}
var lowestQualityJPEGNSData: NSData  { return UIImageJPEGRepresentation(self, 0.0)! as NSData }

}

I've created a func to satisfy thy needs in this case. 在这种情况下,我创建了一个函子来满足您的需求。 Pass the UIImage in 'image' param in the below request. 在以下请求中,在“图像”参数中传递UIImage。

multipartUploadRequestWith(imageData: UIImageJPEGRepresentation(image, 1.0), parameters: params, onCompletion: {
        print("Upload Successful")
    }) { (error) in
        print(error.debugDescription)
}

Below is the code for the function. 下面是该函数的代码。

func multipartUploadRequestWith(imageData: Data?, parameters: [String : Any], onCompletion: (() -> Void)? = nil, onError: ((Error?) -> Void)? = nil){

    let url =  /* your API url */

    let headers: HTTPHeaders = [
        /* "Authorization": "your_access_token",  in case you need authorization header */
        "Content-type": "multipart/form-data",
    ]
    print(headers)
    Alamofire.upload(multipartFormData: { (multipartFormData) in
        for (key, value) in parameters {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
        }

        if let data = imageData{
            multipartFormData.append(data, withName: "photo", fileName: "photo.jpeg", mimeType: "image/jpeg")
        }

    }, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
        switch result{
        case .success(let upload, _, _):
            upload.response { response in
                if let err = response.error{
                    print("This error")
                    let alert = UIAlertController(title: "Upload Failed", message: "The image upload failed. Check your internet connection", preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
                    UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
                    onError?(err)
                    return
                }
                if response.response?.statusCode == 200 {
                    print("Succesfully uploaded")
                    onCompletion?()
                } else {
                    print("Error " )
                }
            }
        case .failure(let error):
            print("Error in upload: \(error.localizedDescription)")
            onError?(error)
        }
    }
}

Try This 尝试这个

func callAPI( _ parameters:[String:Any] , url:String) {


        print(parameters)

        let uploadImageProfileURL = url

        var urlRequest = URLRequest(url: URL(string:uploadImageProfileURL)!)
        urlRequest.httpMethod = "POST"

        urlRequest.allHTTPHeaderFields = [
            "content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
            "cache-control": "no-cache",
        ]

        Alamofire.upload(multipartFormData: { multipartFormData in

            for (key, value) in parameters {
                if value is String {
                    multipartFormData.append((value as! String).data(using: String.Encoding.utf8)!, withName: key )
                }

                if value is UIImage {

                    let imgData = UIImageJPEGRepresentation(value as! UIImage, 1)!

                    multipartFormData.append(imgData, withName: key  ,fileName: "file.jpg", mimeType: "image/jpg")
                }

                if value is Array<UIImage> {

                    let arrayValue = value as! [UIImage]

                    for image in arrayValue {

                        let fileName = "file\(arc4random()%1000).jpg"
                        let mimeType = "application/octet-stream" ?? "image/jpg"
                        let data = UIImageJPEGRepresentation(image, 1)

                        multipartFormData.append(data!, withName: "\(key)", fileName:fileName, mimeType: mimeType)
                    }

                }

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

            switch result {

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

                upload.responseJSON { response in

                    if let JSON = response.result.value {

                    }
                }




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

        }
    }

Alamofire4 and Swift 4.1 Alamofire4和Swift 4.1

1st Step: Take a imageView and pick the image by using imagepickerview After that take a button in which below function will be call 第一步:拍摄一个imageView并使用imagepickerview拍摄一个图像,然后点击一个按钮,在其中调用以下功能

** **

func uploadAvatar() {
            let id : String = UserDefaults.standard.value(forKey: "id") as! String
            let token : String = UserDefaults.standard.value(forKey: "token") as! String
            let url = "http://203.163.248.214:1357/api/user/update_image"
            let headers = ["x-access-token": token]
            showLoader(OnView: view)

        let imageData = self.imgView.image!.jpegData(compressionQuality: 0.7)

        let parameters: [String : AnyObject] = ["user_id": id as AnyObject]

            Alamofire.upload(multipartFormData:{ multipartFormData in
                multipartFormData.append(imageData!, withName: "file", fileName: "file.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
                    })
                    upload.responseJSON
                        { response in
                            let json = response.result.value as! [String:AnyObject]
                            print(json)
                            if response.result.value != nil
                            {
                                if json["status"] as! NSInteger == 200 {

                                    DispatchQueue.main.async(execute: {() -> Void in

                                        self.dismissLoader()
                                        self.userImage = json["data"] as! [String:AnyObject]

                                    })

                                }else{
                                    self.dismissLoader()
                                }
                            }
                    }
                case .failure( _):
                    self.dismissLoader()
                    break
                }
            }
        }*

* *

userImage will be ur array or may be dictionary depends upon the response and declare it globally as var userImage = String: AnyObject userImage将是ur数组,也可能是字典,取决于响应,并将其全局声明为var userImage = String:AnyObject

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Alamofire 5.0.0-beta.3 (Swift 5) 上传图像(多部分) - how to upload image (Multipart) using Alamofire 5.0.0-beta.3 (Swift 5) 如何使用alamofire图像检查分段上传是否成功 - How to check if the multipart upload was successful with alamofire image 如何使用带参数的 Alamofire 在服务器上上传图像 - how to upload Image on server using Alamofire with parameters 如何使用Alamofire上传多部分图像? - How to upload multiple images in multipart using Alamofire? Alamofire Multipart图片上传失败 - Alamofire Multipart image upload failed 在Swift 4中的Alamofire 4中使用multipart上传图像和多个参数 - upload image and multiple parameters using multipart in alamofire 4 in swift 4 我想使用 alamofire swift 5 将图像上传到多部分表单数据 - I want to upload image to multipart form data using alamofire swift 5 如何在iOS,Swift3,Alamofire 4中使用多部分表单数据将图像作为参数上传以及其他参数 - How to upload image as a parameter, with other parameters using multipart form data in ios, swift3, Alamofire 4 如何使用 Alamofire 5 将图像作为多部分数据上传到 aws 预签名 url? - How to upload image to aws pre signed url as multipart data using Alamofire 5? 如何在Alamofire中使用multipart在多个图像阵列中上传多个图像? - How to upload multiple images in multiple array of images using multipart in Alamofire?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM