如何将图像上传为二进制

Zuh*_*ain 1 ios postman swift alamofire

我想以二进制形式上传图像,就像我们在下面在 Postman 中所做的那样

在此输入图像描述

这是我的代码

var url = myURLString
url = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!

guard let imageData = UIImageJPEGRepresentation(image, 0.4) else {
        return
    }

request.httpBody = imageData
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

Alamofire.request(request).responseJSON { (response) in
        if let JSON = response.result.value as? NSDictionary {
            print(JSON)
        } else {
            let message = response.result.error != nil ? response.result.error!.localizedDescription : "Unable to communicate."
            print(message)
        }
 }
Run Code Online (Sandbox Code Playgroud)

看来请求没有附加图像文件,返回以下错误消息

“响应无法序列化,输入数据为零或长度为零。”

Zuh*_*ain 6

对于 swift 3、Alamofire 4,下面的代码可以正常工作

var url = myURLString
url = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
guard let imageData = UIImageJPEGRepresentation(image, 0.4) else {
    return
}

Alamofire.upload(imageData, to: URL(string: url)!, method: .post, headers: nil).responseJSON { (response) in
    if let JSON = response.result.value as? NSDictionary {
        print(JSON)
    } else {
        let message = response.result.error != nil ? response.result.error!.localizedDescription : "Unable to communicate."
        print(message)
    }
}
Run Code Online (Sandbox Code Playgroud)