ios - IOS中带参数上传多部分图片

标签 ios swift alamofire

我是 IOS 新手,想要将带有参数的图像上传到服务器,但它没有上传。我尝试了很多引用 alamofire 和 base64 但没有任何效果对我有用。我是否错过了任何事情,对理解这一点有任何帮助吗?

提前致谢。请帮我解决问题

下面是我的代码:

@IBAction func submitBtnClicked(_ sender: Any)

{
    //parameters
    var number: Int?
    number = 47000482
    var srNumber = String(format:"%d",number!)
    var urlString: String = filePath!.absoluteString
    var parameters = ["s_no":srNumber, "count":"1"]
    let imgData = UIImageJPEGRepresentation(self.chosenImage!, 0.5)

    print(parameters)
    print(imgData)

    Alamofire.upload(multipartFormData: { (multipartFormData) in

        multipartFormData.append(imgData!, withName:"filestream", fileName:(self.filePath?.lastPathComponent)!, mimeType: "image/jpeg")

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

    { (result) in

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

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

            upload.responseJSON { response in
                print(response.request)  // original URL request
                print(response.response) // URL response
                print(response.data)     // server data
                print(response.result)   // result of response serialization

                if let JSON = response.result.value {
                    print("JSON: \(JSON)")
                }
            }

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

最佳答案

    //MARK: - Multiple Images Uploading API Call
        func serviceUploadMultipleImageData(model : UploadImageResponseModel,isLoader:Bool = true,name:String = "", loaderViewcontoller : UIViewController? = nil,url: String, method: HTTPMethod, InputParameter: Parameters?, ServiceCallBack: @escaping (_ Completion: ServiceResponseNormal, _ isSuccess:Bool)-> Void) {
            let viewContoller = loaderViewcontoller
            guard Reachability.isConnectedToNetwork() else {
                Singleton.sharedSingleton.showPopup(title: "No Internet", message: HttpCode.NoInternetConnection.message(), image: nil, VC: viewContoller!)
                ServiceCallBack(self.setCustomResponse(Code: HttpCode.NoInternetConnection.rawValue, Message: "No Internet Connection"),false)
                return
            }
            if isLoader == true {
                if viewContoller != nil {
                    ProgressHUD.startLoading(onView: (viewContoller?.view)!)
                } else {
                    ProgressHUD.startLoading(onView: appDelegate.window!)

                }
            }

            Alamofire.upload(multipartFormData: { (multipartFormData) in

                for obj in model.arrImages{
                multipartFormData.append(obj.imageData!, withName:obj.imgName, fileName: "", mimeType: "image/jpg")
}
                for (key, value) in InputParameter! {
                    multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue, allowLossyConversion: true)!, withName: key)
                }
            }, to:url)
            { (result) in
                switch result {
                case .success(let upload, _, _):

                    upload.uploadProgress(closure: { (Progress) in
                        model.progress = Progress.fractionCompleted
                    })

                    upload.responseJSON { response in
                        if isLoader == true {
                            if viewContoller != nil {
                                ProgressHUD.stopLoading(fromView: (viewContoller?.view)!)
                            }else {
                               ProgressHUD.stopLoading(fromView: appDelegate.window!)
                            }
                        }
                        if(response.result.isSuccess){
                            print(response)
                            do{
                                if response.data != nil{
                                    var responseParsed = try JSONDecoder().decode(ServiceResponseNormal.self, from: response.data!)
                                    if responseParsed.Code == "200"
                                    {
                                        responseParsed.Data = response.data
                                        ServiceCallBack(responseParsed, true)
                                    }
                                    else
                                    {
                                        Singleton.sharedSingleton.showPopup(title: "Error", message: responseParsed.Message ?? "Error", image: nil, VC: viewContoller!)
                                        ServiceCallBack(responseParsed, false)
                                    }
                                }
                            }
                            catch let error {
                                print(error.localizedDescription)
                                var falilure = ServiceResponseNormal()
                                falilure.Data = nil
                                falilure.Message = "Response could not parsed"
                                ServiceCallBack(falilure, false)
                            }
                        }
                        else{
                            if let error = response.result.error{
                                let message = error.localizedDescription
                                var falilure = ServiceResponseNormal()
                                falilure.Data = nil
                                falilure.Message = message
                                ServiceCallBack(falilure, false)
                                Singleton.sharedSingleton.showPopup(title: "Error", message: message, image: nil, VC: viewContoller!)
                            }
                        }
                    }
                case .failure(let encodingError):
                    let message = encodingError.localizedDescription
                    var falilure = ServiceResponseNormal()
                    falilure.Data = nil
                    falilure.Message = message
                    ServiceCallBack(falilure, false)
                    Singleton.sharedSingleton.showPopup(title: "Error", message: message, image: nil, VC: viewContoller!)
                }
            }


        }

关于ios - IOS中带参数上传多部分图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54141662/

相关文章:

ios - Swift - 从 Alamofire POST 请求中获取数据

ios - 将谷歌分析跟踪添加到我的 iOS Today 小部件

ios - 在 iOS 模拟器上运行 DalekJS

ios - 如何隐藏 iOS 图表饼图中的值?

ios - 根据用户选择更改应用本地化

ios - 关闭 View Controller UI 时卡住

iphone - 重新启动游戏时游戏场景崩溃

swift - 为什么这个swift代码是错误的?

swift - 如何在 UITableView 中设置 Section 属性?

swift - 为什么上传 alamofire 后台请求不在后台执行?