使用Alamofire'〜> 5.0.0-beta.3'从multipart-form-data上传图像

问题描述 投票:0回答:2
func uploadImage(image: UIImage, imageUrl: String, imageExtension: String , responseData: @escaping (_ response: UploaderModel)-> ()) {
        var status : UploaderModel?
        let token = UserDefaults.standard.string(forKey: PrefKeys.loginToken) ?? ""
        let authorization = ["Authorization" : "Bearer \(token)"]
        let imageURl = "http://68.183.152.132/api/v1/stuff/uploader"

        //Parameter HERE
        let  parameters = [
                    "garbageCollector": 0,
                    "stuff_uuid": "2b4b750a-f4a6-4d61-84ce-7c42b5c030ee",
                    "delete_file" : ""
            ] as [String : Any]

        //Header HERE
        let headers: HTTPHeaders
         headers = ["Content-type": "multipart/form-data",
                       "Content-Disposition" : "form-data"]

        guard let imgData = firstImage.image?.jpegData(compressionQuality: 0.7) else { return }

        AF.upload(multipartFormData: { multipartFormData in
            //Parameter for Upload files
            multipartFormData.append(imgData, withName: "file",fileName: imageUrl , mimeType: "image/\(imageExtension)")

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

        }, usingThreshold:UInt64.init(),
           to: imageURl, //URL Here
            method: .post,
            headers: headers, //pass header dictionary here
            interceptor: { (result) in

                switch result {
                case .success(let upload, _, _):
                    upload.uploadProgress(closure: { (progress) in
                        print("Uploading")
                    })

                    upload.responseJSON { response in
                        print("the resopnse code is : \(response.response?.statusCode)")
                        print("the response is : \(response.description)")
                        let json = JSON(response.data)
                        if let msg = json["msg"].string {
                            status.msg = msg
                        }
                        if let stat = json["status"].int {
                            status.status = stat
                        }
                        responseData(status)
                    }
                    break
                case .failure(let encodingError):
                    print("the error is  : \(encodingError.localizedDescription)")
                    break
                }
                } )
    }

error : Cannot convert value of type '(_) -> ()' to expected argument type 'RequestInterceptor?'
ios swift file-upload alamofire multipartform-data
2个回答
2
投票

// swift 5

static func postComplexPictures(url:URL, params:[String:Any],pictures : UIImage, finish: @escaping ((message:String, list:[[String: Any]],isSuccess:Bool)) -> Void) {

        var result:(message:String, list:[[String: Any]],isSuccess:Bool) = (message: "Fail", list:[],isSuccess : false)

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

        AF.upload(multipartFormData: { (multipartFormData) in

            for (key, value) in params {
                multipartFormData.append((value as! String).data(using: String.Encoding.utf8)!, withName: key)
            }
                if let imageData = pictures.pngData() {
                    multipartFormData.append(imageData, withName: "document", fileName: "document.png", mimeType: "image/png")
            }
        }, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers).response{ response in

            if((response.error != nil))
           {
                do
                {
                    if let jsonData = response.data
                    {
                        let parsedData = try JSONSerialization.jsonObject(with: jsonData) as! Dictionary<String, AnyObject>
                        print(parsedData)

                        let status = parsedData["status"] as? NSInteger ?? 0
                        let msg = parsedData["message"] as? String ?? ""


                        if(status==1)
                        {
                            result.isSuccess = true
                            result.message=msg
                            if let jsonArray = parsedData["data"] as? [[String: Any]] {
                                result.list=jsonArray
                            }
                        }
                        else
                        {
                            result.isSuccess = false
                            result.message=msg
                        }

                    }
                    finish(result)
                }
                catch
                {
                   finish(result)
                }
            }
            else
            {
            finish(result)
            }

        }
    }


0
投票

Vishal Darvara的解决方案有点清晰,可以回答Alamofire 5。

    func uploadPhoto(_ url: String, image: UIImage, params: [String : Any], header: [String:String], completion: @escaping (JSON) -> ()) {
    let httpHeaders = HTTPHeaders(header)
    lastRequest = AF.upload(multipartFormData: { multiPart in
        for p in params {
            multiPart.append("\(p.value)".data(using: String.Encoding.utf8)!, withName: p.key)
        }
       multiPart.append(image.jpegData(compressionQuality: 0.4)!, withName: "avatar", fileName: "file.jpg", mimeType: "image/jpg")
    }, to: url, method: .post, headers: httpHeaders) .uploadProgress(queue: .main, closure: { progress in
        print("Upload Progress: \(progress.fractionCompleted)")
    }).responseJSON(completionHandler: { data in
        print("upload finished: \(data)")
    }).response { (response) in
        switch response.result {
        case .success(let resut):
            print("upload success result: \(resut)")
        case .failure(let err):
            print("upload err: \(err)")
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.