如何使用 multipartFormData 和参数上传图像,使用 Alamofire 4.3 请求所需的身份验证

Posted

技术标签:

【中文标题】如何使用 multipartFormData 和参数上传图像,使用 Alamofire 4.3 请求所需的身份验证【英文标题】:How to Upload image using multipartFormData and parameter, request required authentication using Alamofire 4.3 【发布时间】:2017-06-01 06:55:38 【问题描述】:

你能帮我上传图片MultipartFormData 参数和请求身份验证。

let username = "username"
let password = "password"

用于请求认证

    let kurl = "Server url"
    let headers: HTTPHeaders = ["Authorization":"Basic \(base64EncodedCredential)"]
    let parmeter = ["name":"taykun","is_user":"1"]

        Alamofire.upload(multipartFormData:  (multipartFormData) in

                    , to: kurl, encodingCompletion:  (result) in

                    )

【问题讨论】:

【参考方案1】:

为 alamofire 试试这个代码:

   func uploadImageWithData(strApiUrl:String,strImageUrl:String,param:Dictionary<String, String>? = nil ,completionHandler: @escaping (_ result: NSDictionary) -> Void) -> Void
            Alamofire.upload(multipartFormData:  multipartFormData in
                let urlImage:URL = URL.init(fileURLWithPath: strImageUrl)
                multipartFormData.append(urlImage, withName: "your key for image use in API")
                for (key, value) in param! 
                    multipartFormData.append(value.data(using:String.Encoding(rawValue: String.Encoding.utf8.rawValue))!, withName: key)
                
            , to: strApiUrl, encodingCompletion: 
                (encodingResult) in
                print("encoding result:\(encodingResult)")
                switch encodingResult 
                case .success(let upload, _, _):
                    upload.uploadProgress(closure:  (Progress) in
                        print("Upload Progress: \(Progress.fractionCompleted)")
                        //send progress using delegate
                    )
                    upload.responseJSON (response) in                    
                case .failure(let encodingError):
                    print(encodingError)
                
            )

        


    func returnResponse (response: DataResponse<Any>)->NSDictionary
        
            if (response.result.isSuccess)
            
                if let value = response.result.value
                
                    return value as! NSDictionary
                
            
            else
            
                print("\(response.error?.localizedDescription)")
                var statusCode = 0
                if let error = response.result.error as? AFError 
                    statusCode = error._code // statusCode private
                    switch error 
                    case .invalidURL(let url):
                        print("Invalid URL: \(url) - \(error.localizedDescription)")
                    case .parameterEncodingFailed(let reason):
                        print("Parameter encoding failed: \(error.localizedDescription)")
                        print("Failure Reason: \(reason)")
                    case .multipartEncodingFailed(let reason):
                        print("Multipart encoding failed: \(error.localizedDescription)")
                        print("Failure Reason: \(reason)")
                    case .responseValidationFailed(let reason):
                        print("Response validation failed: \(error.localizedDescription)")
                        print("Failure Reason: \(reason)")

                        switch reason 
                        case .dataFileNil, .dataFileReadFailed:
                            print("Downloaded file could not be read")
                        case .missingContentType(let acceptableContentTypes):
                            print("Content Type Missing: \(acceptableContentTypes)")
                        case .unacceptableContentType(let acceptableContentTypes, let responseContentType):
                            print("Response content type: \(responseContentType) was unacceptable: \(acceptableContentTypes)")
                        case .unacceptableStatusCode(let code):
                            print("Response status code was unacceptable: \(code)")
                            statusCode = code
                        
                    case .responseSerializationFailed(let reason):
                        print("Response serialization failed: \(error.localizedDescription)")
                        print("Failure Reason: \(reason)")
                        // statusCode = 3840 ???? maybe..
                    

                    print("Underlying error: \(error.underlyingError)")
                 else if let error = response.result.error as? URLError 
                    print("URLError occurred: \(error)")
                else if let error = response.result.error as? NSError
                  print("timeout")
                   statusCode = error._code
                else 
                    print("Unknown error: \(response.result.error)")
                

                print(statusCode)
                //make a response with nil value and set error or other information in it and return it.
                let paramDic:NSMutableDictionary = NSMutableDictionary()
                paramDic[KEY_MESSAGE] = response.error?.localizedDescription
                paramDic[KEY_DATA] = nil
                paramDic[KEY_STATUS_CODE] = "\(statusCode)"
                paramDic[KEY_SUCCESS] = 0

                return paramDic as NSDictionary
            
            return NSDictionary()
        

以这种方式调用此方法:

 let imgUrl = //first store  your image locally and then set image url
var dicParam = Dictionary<String , String>()//your requestparameter dictionary
        API.uploadImageWithData(strApiUrl: webserviceurl, strImageUrl: imgUrl, param: dicParam, completionHandler:  (result) in
          print(result)
          if result[KEY_SUCCESS] as! Int == 1
           //success
          else
            //fail
          
        )

【讨论】:

请求 url 需要基本身份验证,例如 let username = "username" let password = "password" 我怎样才能通过这个? 简单的制作参数字典并传递给 func like,var dicParam = Dictionary() dicParam["uuername"] = "name" dicParam["password"] = "password" HTTPHeaders = 需要身份验证 你使用post方式还是get方式? Alamofire.request(strUrl, method: HTTPMethod, parameters: param, encoding: URLEncoding.default, headers: nil).validate().responseJSON (response) in completionHandler(self.returnResponse(response : 响应))

以上是关于如何使用 multipartFormData 和参数上传图像,使用 Alamofire 4.3 请求所需的身份验证的主要内容,如果未能解决你的问题,请参考以下文章

玩 2.4:如何使用 MultipartFormData 编写文件上传测试用例

如何使用 multipartFormData 和参数上传图像,使用 Alamofire 4.3 请求所需的身份验证

如何使用 Alamofire 和会话管理器附加 MultipartFormData 以及其他帖子参数? [复制]

Alamofire,使用参数中的结构上传 MultipartFormData

请详细描绘如何使用latex 模版撰写科研论文,在论文中如何插入图片、公式和参

使用 multipartFormData 上传图像时 Alamofire 请求正文为零