【问题标题】:How can I upload image with JSON parameters with Alamofire in Swift?如何在 Swift 中使用 Alamofire 上传带有 JSON 参数的图像?
【发布时间】:2016-03-06 04:01:46
【问题描述】:

我需要将图像上传到服务器端点,其结构必须如下:

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

如何使用 Alamofire 发送这样的请求?

我试过了,但结果是错误消息Invalid type in JSON write (NSConcreteData) 这是我的代码:

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

我关注了这个code

如果有其他方法请指教,谢谢。

【问题讨论】:

  • 尝试使用 base64EncodedStringWithOptions 而不是 base64EncodedDataWithOptions

标签: ios json swift alamofire


【解决方案1】:

我使用的这个方法你可能会觉得很有用

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

【讨论】:

  • 哇,谢谢它的工作。我想问一下 Encoding64CharacterLineLength 是什么,我可以用空数组替换它吗?
  • 不,你不能。这是一种将图像数据转换为可以附加到 JSON 并作为参数发送的长字符串的方法
  • 您可以创建一个不同的数组并将base64字符串附加到它并发送
猜你喜欢
  • 2014-12-17
  • 2017-07-25
  • 2017-07-14
  • 2020-07-10
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2018-02-14
  • 1970-01-01
相关资源
最近更新 更多