简体   繁体   中英

How can I upload image with JSON parameters with Alamofire in Swift?

I need to upload an image to the server endpoint where the structure has to be as following:

    {
        "name": "",
        "description": "",
        "photo": imageFile
    }

How can I send such a request using Alamofire?

I tried this but the result is error with error message Invalid type in JSON write (NSConcreteData) This is my code :

    let imageData = UIImagePNGRepresentation(image)
    let base64String = imageData!.base64EncodedDataWithOptions([])
    
    let parameters = [
        "name": "name",
        "description": "desc",
        "photo": base64String
    ]
    
    let credentialData = "\(id):\(secret)".dataUsingEncoding(NSUTF8StringEncoding)!
    let base64Credentials = credentialData.base64EncodedStringWithOptions([])
    let headers = ["Authorization": "Basic \(base64Credentials)"]

    Alamofire.request(.POST, "", parameters: parameters, encoding: .JSON, headers: headers).responseJSON { (response) -> Void in
        print(response)
    }

And I followed this code

If there is another way to do please advice, thanks.

This method I'm using you might find it useful

let image : UIImage = image.image!
let imageData = UIImagePNGRepresentation(image)
let base64String = imageData!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM