上传 uiimage base64 编码
Posted
技术标签:
【中文标题】上传 uiimage base64 编码【英文标题】:Upload uiimage base64 encoded 【发布时间】:2016-11-30 16:38:46 【问题描述】:我正在尝试上传 uiview(图表),但我通过电子邮件(来自 web 服务)收到空图片...android 正在运行
UIGraphicsBeginImageContext(self.view.bounds.size);
self.view.layer.render(in: UIGraphicsGetCurrentContext()!)
let screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
let jpegCompressionQuality: CGFloat = 1
let imgData:Data = UIImageJPEGRepresentation(screenShot!,jpegCompressionQuality)!
let lengthOfData = imgData.count
let strBase64 = imgData.base64EncodedString(options: [])
var request = URLRequest(url: URL(string: "http://myws.com/Chart.php")!)
request.httpMethod = "POST"
let postString = "data=\(strBase64)&email=admin@myws.com"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("\(lengthOfData)", forHTTPHeaderField: "Content-Length")
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request) data, response, error in
guard let data = data, error == nil else
print("error=\(error)")
return
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200
print("statusCode \(httpStatus.statusCode)")
print("response = \(response)")
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
task.resume()
【问题讨论】:
我认为您在这里遗漏了一些东西,例如为 httpheaderfield 设置值等。 【参考方案1】:您的 ios 设备屏幕截图代码很好。我认为您将 UIImage 上传到服务器的发布请求缺少以下内容:
let imgData:NSData = data
let lengthOfData = imgData.length
// ENCODINGDATA - whatever encoding your server wants here
request.addValue(ENCODINGDATA, forHTTPHeaderField: "Content-Type")
request.addValue("\(lengthOfData)", forHTTPHeaderField: "Content-Length")
除此之外,最好使用AlamoFire
来处理此类复杂的服务器任务。它使它更容易。可以这样实现
let imageData = UIPNGRepresentation(image)!
Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON response in
debugPrint(response)
请随时提出修改建议以使其变得更好。如果我的回答有任何错误或缺点,请告诉我
【讨论】:
服务器收到的图片还是空的吗? 是的,使用UIImageWriteToSavedPhotosAlbum(screenShot!, nil, nil, nil)
图像可以正确进入手机存储
尝试使用Alamofire
库上传图片并检查是否正在上传github.com/Alamofire/Alamofire
我使用了multipart 并且工作正常。谢谢!以上是关于上传 uiimage base64 编码的主要内容,如果未能解决你的问题,请参考以下文章
将 zlib 压缩的 base64 字符串转换为 Uiimage 的问题