在IOS中上传带参数的多部分图像

Posted

技术标签:

【中文标题】在IOS中上传带参数的多部分图像【英文标题】:Upload multipart image with parameters in IOS 【发布时间】:2019-01-11 06:52:26 【问题描述】:

我是 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)
        
    

【问题讨论】:

你能告诉我错误吗?你能上传整个代码让我调试吗? 在此处发布之前正确格式化您的代码。 在请求中添加 HttpMethod。您可以在标题中尝试“Content-Type:Multipart/*”。 【参考方案1】:
    //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!)
                
            


        

【讨论】:

【参考方案2】:

首先,您需要添加方法类型,即 .post 或 .put 类型以及 url,然后您将能够发送图像数据并增加会话请求的超时间隔manager.session。 configuration.timeoutIntervalForRequest = 120如果您有任何疑问,请回复我,我会尽力解决您的问题。

class func requestForAPI(param:Dictionary<String, String>?, Url:String,image:UIImage,isShowLoader:Bool, headers:[String:String]?,  completion: @escaping (_ result: AnyObject?, _ error: Error?) -> Void) 

  let reach:Reachability = Reachability.forInternetConnection()
  let netStatus:NetworkStatus = reach.currentReachabilityStatus()
if (netStatus == NotReachable)


    NSUtility.shared().showMessage(title: "Alert!", body: "Please connect to the internet to continue", themetype: .error)

    return


if isShowLoader == true
    APPDELEGATE?.showLoaderView()


let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 120
let  imageData = image.jpegData(compressionQuality: 0.8)

manager.upload(multipartFormData:
    
        (multipartFormData) in
        multipartFormData.append(imageData, withName: "file", fileName:    "file.jpeg", mimeType: "image/jpeg") for (key, value) in param 
             multipartFormData.append(value.data(using:String.Encoding.utf8.rawValue)!, withName: key)

, to:URL(string: Url)!,method:.put, headers:headers)
 (result) in
    switch result 
    case .success(let upload,_,_ ):
        upload.uploadProgress(closure:  (progress) in
            //Print progress
        )
        upload.responseJSON
             response in
                APPDELEGATE?.dismissLoader()

                //print response.result
                if response.result.value != nil
                

                    print (response.result.value as Any)
                    completion(response.result.value as AnyObject? , nil)
                
        
    case .failure(let encodingError):
          print(encodingError)
          completion(nil, encodingError)
        break
    
  

【讨论】:

以上是关于在IOS中上传带参数的多部分图像的主要内容,如果未能解决你的问题,请参考以下文章

无法使用 alamofire 4 上传带参数的图像?

如何在上传带参数的图像时使用 AFNetworking 2.0 设置 cookie?

alamofire上传带json参数的图片

NSURLSessionUploadTask 不上传带参数的图片

AFNetworking 上传带参数的图片

C# 中怎么使用带参数的多线程呢