在Swift中使用Alamofire使用参数上传图像

时间:2017-03-06 06:43:42

标签: ios swift alamofire

我正在使用Alamofire将数据发布到服务器上。我想用一些其他参数以数据形式上传到服务器的图像。在Alamofire中,我使用multipartFormData方法发布所有参数和图像。服务器需要数据为JSON格式,参数如下所示:

 {"product_name": "almondsfdsfsdf",
 "product_price": "400",
 "product_img": image.jpg}

我正在尝试,但它让我失败了。以下是我在alamofire中快速做的事情的代码:

let productName = itemNameTF.text!
let productPrice = itemPriceTF.text!
let productImage:UIImage = itemImage.image!
let url = "URL"
let parameter = ["product_name": productName, "product_price": productPrice]
let headers : HTTPHeaders = ["Content-Type": "application/json","Authorization" : "Token abcd"]
Alamofire.upload(multipartFormData: {
            multipartFormData in
            if let imageData = UIImageJPEGRepresentation(productImage, 0.5){
                multipartFormData.append(imageData, withName: "image", fileName: "file.png", mimeType: "image/png")
            }

            for (key,value) in parameter {
                multipartFormData.append(value.data(using: .utf8)!, withName: key)
            }
        }, to: url,method: .post, headers: headers, encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload,_,_):
                upload.responseJSON { response in

                    print(response.request)
                    print(response.response)
                    print(response.result)
                    print(response.data)
                }
                break
            case .failure(let encodingError):
                print("error: \(encodingError)")
                break
            }
        })

我的服务器接受BLOB数据中的图像。如果有人可以帮助我。谢谢!

2 个答案:

答案 0 :(得分:0)

尝试更改此行:

multipartFormData.append(imageData, withName: "image", fileName: "file.png", mimeType: "image/png")

对此:

multipartFormData.append(imageData, withName: "product_img", fileName: "image.jpg", mimeType: "image/jpeg")

答案 1 :(得分:0)

请参考以下方法获得答案(适用于Alamofire 3.0 +)。

func uploadImageAndData(){

    var parameters = [String:AnyObject]()
    parameters = ["token":token,
                  "lastName":lastName]

    let URL = "http://yourserviceurl/"
    let image = UIImage(named: "image.png")

    Alamofire.upload(.POST, URL, 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 parameters {
            multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
        }
    }, encodingCompletion: {
        encodingResult in

        switch encodingResult {
        case .Success(let upload, _, _):
            print("s")
            upload.responseJSON { 
                response in
                print(response.request)  // original URL request
                print(response.response) // URL response
                print(response.data)     // server data
                print(response.result)   // result of response serialization

                if let JSON = response.result.value {
                    print("JSON: \(JSON)")
                }
            }
        case .Failure(let encodingError):
            print(encodingError)
        }
    })
}