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

问题描述 投票:0回答:2

我想将图像上传为二进制文件,如下面的邮递员所示

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

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

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

ios swift alamofire postman
2个回答
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 { }
})

1
投票

对于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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.