带参数和标题的Alamofire多部分图像上传 - Swift

时间:2018-01-31 23:29:25

标签: swift api post alamofire multipartform-data

我们需要使用POST方法,参数和令牌将图像上传到API。

这是我们的代码:

 func myImageUploadRequest()
{
    var boole : String!
    if(card) {
        boole = "1"
    }
    else {
        boole = "0"
    }
    let headers: HTTPHeaders = ["Authorization": "Token \(token!)"]
    print(headers.debugDescription)

    let param = [
        "comment":comment,
        "category":String(category),
        "amount":String(money),
        "payment_card":boole
    ]
    Alamofire.upload(method:.post,"https://llegoelbigotes.ubiqme.es/api/new-ticket/",headers:headers, multipartFormData: {
        multipartFormData in
        if let imageData = UIImageJPEGRepresentation(image,0.6) {
            multipartFormData.appendBodyPart(data:imageData,name:"image",fileName:"file.png",mimeType: "image/png")
        }
        for(key,value) in param {
            multipartFormData.appendBodyPart(data:value.dataUsingEncoding(NSUTF8StringEncoding)!,name:key)
        }
    }, encdingCompletion: {
            encodingResult in
        switch encodingResult {
        case .Success(let upload, _, _):
            print("Success")
        upload.responseJSON{ response in
            print(response.request)
            print(response.response)
            print(response.data)
            print(response.result)
        if let JSON = response.result.value {
        print("JSON: \(JSON)")
        }
    }
        case .Failure(let encodingError):
        print(encodingError)
        }
    })


}

此代码给出了一个错误:

  

对成员'上传(_:to:method:headers :)的不明确的引用'

知道出了什么问题?

1 个答案:

答案 0 :(得分:1)

认为你得到了参数的顺序错误。

 Alamofire.upload(multipartFormData: { multipartFormData in
            // multipartFormData here
        },
        to: url,
        method: .post,
        headers: headers) { encodingResult in
            // results here
        }