how to upload an Image using alamofire with basic authentication?

ぐ巨炮叔叔 提交于 2019-12-11 00:54:09

问题


I am trying to upload an image using alamofire 4.7.1 with this code, but to be honest I suspect that I didn't write a right code to upload the image

func uploadDefect(defectRemark: String, defectLocation: String, defectImage: UIImage, fileNameImage: String, completion: @escaping(_ errorMessage: String?) -> Void) {

        guard let imgData = defectImage.jpeg(.medium) else {return}

        let urlUpload = URLService.uploadDefect.endPoint

        let username = "admin"
        let password = "1234"

        let credentialData = "\(username):\(password)".data(using: String.Encoding.utf8)!
        let base64Credentials = credentialData.base64EncodedString(options: [])
        let headers = ["Authorization": base64Credentials]
        let parameters : [String:Any] = ["defect_remark" : defectRemark, "defect_location": defectLocation, "tenant_id" : tenantID]

        let url = try! URLRequest(url: URL(string: urlUpload)!, method: .post, headers: headers)

        Alamofire.upload(
            multipartFormData: { multipartFormData in
                multipartFormData.append(imgData, withName: "file", fileName: fileNameImage, mimeType: "image/jpeg")

                for (key, value) in parameters {
                    multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
                }
        },
            with: url,
            encodingCompletion: { encodingResult in

                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in

                        print("upload response: \(response)")

                        switch response.result {
                        case .failure(let error) :
                            let message : String
                            if let httpStatusCode = response.response?.statusCode {
                                switch(httpStatusCode) {
                                case 404:
                                    message = "File not found"
                                case 500 :
                                    message = "Internal Error"
                                default:
                                    message = "Connection issue, please make sure you have a good internet access, or please contact IT Support."
                                }
                            } else {
                                message = error.localizedDescription
                            }

                            completion(message)
                        case .success( _) :
                            completion(nil)
                        }
                    }

                case .failure(let encodingError):
                    let messageEncodingError = encodingError.localizedDescription
                    print(encodingError)
                    completion(messageEncodingError)
                    break
                }
        }
        )




    }

it seems that case .success is triggered

case .success( _) :
  completion(nil)
}

but seems no error, but I didn't get the expected JSON response from the server.

here is the error log from the debugging area

I suspect that I didn't write a right code to upload the image server using alamofire using basic authentication. could you please help me with this one?


回答1:


Change your Authorization like this:

let headers = ["Authorization": "Basic \(base64Credentials)"]

You can also make use of Alamofire to create the authentication header like:

var headers: HTTPHeaders = [:]

if let authorizationHeader = Request.authorizationHeader(user: user, password: password) {
    headers[authorizationHeader.key] = authorizationHeader.value
}


来源:https://stackoverflow.com/questions/50342214/how-to-upload-an-image-using-alamofire-with-basic-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!