Agung
Agung

Reputation: 13803

How to upload an image using alamofire multipart form data with basic authentication?

I am new in programming and in iOS development. I need to upload an image using Alamofire multipart form data, but I also need to input basic authentication header.

in this thread Alamofire 4.0 Upload MultipartFormData Header, it seems similar to my problem, the code is like this to upload

Alamofire.upload(multipartFormData:{ multipartFormData in
         multipartFormData.append(unicornImageURL, withName: "unicorn")
         multipartFormData.append(rainbowImageURL, withName: "rainbow")},
       usingThreshold:UInt64.init(),
       to:"https://httpbin.org/post",
       method:.post, 
       headers:["Authorization": "auth_token"], 
       encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint(response)
            }
        case .failure(let encodingError):
            print(encodingError)
        }
    })

but I am confused how to put the basic authentication (i.e username & password) header. and I also confused where I should place my image data.

I find another thread that seems similar to my problem. here it is... How to upload MultipartFormData with authentication using Alamofire, the proposed solution is this code :

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

let credentialData = "\(username):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!                  
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
let headers = ["Authorization": base64Credentials]

Alamofire.upload(
    .POST,
    "https://rilbits.com/supersafe/photo/upload",
    headers: headers,
    multipartFormData: { multipartFormData in
        let data = "default".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
        multipartFormData.appendBodyPart(data: data, name: "_formname")
        multipartFormData.appendBodyPart(fileURL: fileURL, name: "photo")
    },
    encodingCompletion: { encodingResult in
        switch encodingResult {

        case .Success(let upload, _, _):
            upload.responseString { response in
                debugPrint(response)
            }

        case .Failure(let encodingError):
            print(encodingError)
        }
    }
)

but after fixing to the swift 4.1 it gives an error :

enter image description here

could you please help my problem? Thanks in advance :)

Upvotes: 1

Views: 4763

Answers (3)

Deepak
Deepak

Reputation: 734

Use :

Alamofire.upload(multipartFormData:{ multipartFormData in
            multipartFormData.append(data, withName: "_formname") 
            multipartFormData.append(fileURL, withName: "photo")},
                         usingThreshold:UInt64.init(),
                         to:"URL",
                         method:.post,
                         headers:["Authorization": "auth_token"],
                         encodingCompletion: { encodingResult in
                            switch encodingResult {
                            case .success(let upload, _, _):
                                upload.responseJSON { response in
                                    debugPrint(response)
                                }
                            case .failure(let encodingError):
                                print(encodingError)
                            }
        })

Upvotes: 0

Agung
Agung

Reputation: 13803

i finally found the answer, kindly please use my code below

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 parameters : [String:Any] = ["defect_remark" : defectRemark, "defect_location": defectLocation, "tenant_id" : tenantID]



    var headers: HTTPHeaders = [:]

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

    Alamofire.upload(
        multipartFormData: { multipartFormData in

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

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


    },
        to: urlUpload,
        headers: headers,
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    debugPrint(response)
                }
            case .failure(let encodingError):
                print(encodingError)
            }
    }
    )


}

Upvotes: 1

Manish Mahajan
Manish Mahajan

Reputation: 2082

I have created this function: Hope it works for you:-

 //Alamofire file upload code
func requestWith(URLString: String,
                 imageData: Data?,
                 fileName: String?,
                 pathExtension: String?,
                 parameters: [String : Any],
                 onView: UIView?,
                 vc: UIViewController,
                 completion:@escaping (Any?) -> Void,
                 failure: @escaping (Error?) -> Void) {

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

    let URL = BASE_PATH + URLString
    Alamofire.upload(multipartFormData: { (multipartFormData) in
        for (key, value) in parameters {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
        }

        if let data = imageData {
            multipartFormData.append(data, withName: "fileUpload", fileName: "\(fileName!).\(pathExtension!)", mimeType: "\(fileName!)/\(pathExtension!)")
        }

    }, usingThreshold: UInt64.init(), to: URL, method: .post, headers: headers) { (result) in

        switch result {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                if let err = response.error {
                    failure(err)
                    return
                }
                completion(response.result.value)
            }
        case .failure(let error):
            print("Error in upload: \(error.localizedDescription)")
            failure(error)
        }
    }
}

Upvotes: 2

Related Questions