如何将图像上传为二进制

Posted

技术标签:

【中文标题】如何将图像上传为二进制【英文标题】:How to Upload Image as Binary 【发布时间】:2017-12-26 08:13:21 【问题描述】:

我想将图片作为二进制文件上传,就像我们在下面的 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)
        
 

请求好像没有附加图片文件,返回如下错误信息

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

【问题讨论】:

为什么不直接使用Alamofire.upload(…) alamofire.error Code=-6006 "JSON could not be serialized的可能重复 尝试 responseString 而不是 responseJSON 并检查您遇到了什么错误。 【参考方案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)
    

【讨论】:

如果没有 Alamofire,我将如何做到这一点?我试图避开图书馆。【参考方案2】:

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

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  
)

【讨论】:

【参考方案3】:

Swift 4 和 5

var urlRequest = URLRequest(url: URL)
urlRequest.httpMethod = "PUT" // POST
urlRequest.setValue("image/jpeg", forHTTPHeaderField: "Content-Type")
var data = image!.jpegData(compressionQuality: CGFloat(0.5))!
URLSession.shared.uploadTask(with: urlRequest, from: data, completionHandler:  responseData, response, error in
       DispatchQueue.main.async 
                print(response)
                guard let responseCode = (response as? HTTPURLResponse)?.statusCode, responseCode == 200  else 
                     if let error = error 
                            print(error)
                      
                      return
                  
                          // do your work
              
).resume()

【讨论】:

以上是关于如何将图像上传为二进制的主要内容,如果未能解决你的问题,请参考以下文章

如何将内存中的图像上传为 Flutter web 中 body 上的二进制图像?

MongoDB & Multer - 如何将缓冲区二进制文件转换为图像?

如何将上传的图像保存到 MongoDB 集合并检索它

java图像上传中如何判断是不是是jpg格式

如何在opencv中将绘制在图像上的画笔绘图保存为填充和单独的二进制掩码?

如何在 R 中将图像上传到 SQL Server