如何将图像作为二进制上传

时间:2017-12-26 08:13:21

标签: ios swift alamofire postman

我想将图片上传为二进制文件,如我们在下面的Postman中所做的那样

enter image description here

这是我的代码

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

似乎请求未附加图像文件,返回以下错误消息

  

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

我正在从图库中检索图像,并使用以下代码获取图像的名称: 你可以使用以下功能。

func createMultipart(image: UIImage, callback: Bool -> Void){
    // use SwiftyJSON to convert a dictionary to JSON
    var parameterJSON = JSON([
        "id_user": "test"
    ])
    // JSON stringify
    let parameterString = parameterJSON.rawString(encoding: NSUTF8StringEncoding, options: nil)
    let jsonParameterData = parameterString!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
    // convert image to binary
    let imageData = UIImageJPEGRepresentation(image, 0.7)
    // upload is part of AlamoFire
    upload(
        .POST,
        URLString: "use your url here",
        multipartFormData: { multipartFormData in
            // fileData: puts it in "files"
            multipartFormData.appendBodyPart(fileData: jsonParameterData!, name: "goesIntoFile", fileName: "json.txt", mimeType: "application/json")
            multipartFormData.appendBodyPart(fileData: imageData, name: "file", fileName: "ios.jpg", mimeType: "image/jpg")
            // data: puts it in "form"
            multipartFormData.appendBodyPart(data: jsonParameterData!, name: "goesIntoForm")
        },
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON { request, response, data, error in
                    let json = JSON(data!)
                    println("json:: \(json)")
                    callback(true)
                }
            case .Failure(let encodingError):
                callback(false)
            }
        }
    )
}

let fotoImage = UIImage(named: "foto")
    createMultipart(fotoImage!, callback: { success in
    if success { }
})