如何使用带有基本身份验证的alamofire多部分表单数据上传图像?

时间:2018-05-14 09:27:36

标签: ios swift file-upload alamofire multipartform-data

我是编程和iOS开发的新手。我需要使用Alamofire多部分表单数据上传图像,但我还需要输入基本身份验证标题。

在这个帖子Alamofire 4.0 Upload MultipartFormData Header中,它似乎与我的问题类似,代码就是这样上传

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)
        }
    })

但我很困惑如何放置基本身份验证(即用户名和密码)标头。而且我也很困惑我应该放置我的图像数据。

我找到了另一个与我的问题类似的线程。这是... How to upload MultipartFormData with authentication using Alamofire,建议的解决方案是这段代码:

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)
        }
    }
)

但是在修复到swift 4.1之后它会出错:

enter image description here

你可以帮忙解决我的问题吗?在此先感谢:)

3 个答案:

答案 0 :(得分:0)

我已创建此功能:希望它适合您: -

 //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)
        }
    }
}

答案 1 :(得分:0)

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)
                            }
        })

答案 2 :(得分:0)

我终于找到了答案,请使用下面的代码

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)
            }
    }
    )


}