Swift 4 Alamofire和编码UIImage时遇到问题

时间:2018-11-29 04:35:48

标签: swift alamofire swift4.2.1

使用post和Swift 4,Xcode 10和Alamofire将UIImage发送到我的服务器API时遇到麻烦。 我在Xcode中遇到的错误是:由于格式不正确,无法写入数据。预先感谢您的帮助。

    func saveImage(image: UIImage?) {
    guard let imageToSave = image else {
        return
    }
    guard let imageData = imageToSave.pngData() else {
        return
    }
    let jsonUrlString = "http://192.168.1.5:8080/json/\(imageData)/uploadUserImage"
    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted

    do {
        let jsonData = try encoder.encode(imageData)

        postImageAF(url: jsonUrlString, data: jsonData) { (err, result) in
            if(err != nil) {
                print("error in postWithAlamofire \(err!.localizedDescription)")
                return
            }
            print("result in postWithAlamofire \(result ?? "no result")")
        }
    } catch {
        print(error.localizedDescription)
        print("error in postWithAlamofire \(error.localizedDescription)")
    }
}

func postImageAF(url: String, data: Data, callback: @escaping (Error?, String?) -> Void) {

    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = data

    Alamofire.request(request).responseData { response in
         print("Request: \(String(describing: response.request))")   // original url request
        print("Response: \(String(describing: response.response))") // http url response
        print("Result: \(response.result)")                         // response serialization result
    }
}

1 个答案:

答案 0 :(得分:2)

如果您在服务器端使用multipartFormData类型,请按照以下代码上载图像:

let imgData = newImage.jpegData(compressionQuality: 0.2)!

let imageName = "testImage.jpg"

Alamofire.upload(multipartFormData: { multipartFormData in


    multipartFormData.append(imgData, withName: "file",fileName: imageName, mimeType: "image/jpeg")

}, to:urlString) { (result) in
switch result {

case .success(let upload, _, _):

upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})

upload.responseJSON { response in
print("response.result :\(String(describing: response.result.value))")
}

case .failure(let encodingError):
print(encodingError)
}
}