我所要做的就是让用户选择照片,将其上传到服务器上,然后解码回去并显示出来。我现在正在做的是对图像进行编码,然后将其作为Base64
传递给模型。我将其存储为bytea
在PosgtgreSQL
中。
let imageb: NSData = UIImageJPEGRepresentation(image, 0.7)! as NSData
let dataDecoded: String = imageb.base64EncodedString(options: .lineLength64Characters)
let imageStr: String = dataDecoded.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
然后在我的模型中
private var JSON: [String: Any] {
get {
return ["data": self.imageData]
}
}
然后我使用
Alamofire
将其发布到服务器上APILayer.shared.request(parameters: self.JSON, url: "photo/create", method: .post) { responce in
//some handling stuff
}
服务器端客户端网关方法
let photos = user.getPhotos()
try! response.setBody(json: PhotoDocument.jsonFrom(array: photos))
对象方法
func getPhotos() -> [PhotoDocument] {
return PhotoDocumentMapper.search(id: self.id)
}
private var JSON: [String: Any] {
get {
return ["description": self.description, "importancy": self.importancy, "date": self.date, "data": self.imageData, "id": self.id]
}
}
class func jsonFrom(array: [PhotoDocument]) -> [String: Any] {
var jsons: [Any] = []
for photo in array {
jsons.append(photo.JSON)
}
return ["photos" : jsons]
}
数据映射器方法
class func search(id: Int) -> [PhotoDocument] {
let p = PGConnection()
let _ = p.connectdb("host=localhost port=5432 dbname=perfect")
let result = p.exec(statement: "select * from \"Photos\" where \"userId\" = $1", params: [id])
p.close()
var photos: [PhotoDocument] = []
let resultsNumber = result.numTuples() - 1
if resultsNumber != -1 {
for index in 0...resultsNumber {
let id = result.getFieldInt(tupleIndex: index, fieldIndex: 0)!
let description = result.getFieldString(tupleIndex: index, fieldIndex: 4)!
let date = result.getFieldString(tupleIndex: index, fieldIndex: 5)!
let imageData = result.getFieldString(tupleIndex: index, fieldIndex: 3)!
let importancy = result.getFieldInt(tupleIndex: index, fieldIndex: 2)!
let userId = result.getFieldInt(tupleIndex: index, fieldIndex: 1)!
let photo = PhotoDocument(userId: userId, description: description, date: date, id: id, imageData: imageData, importancy: importancy)
photos.append(photo)
}
}
return photos
}
然后我收到了所有这些数据,并收到了巨大的
String
并尝试了此操作,但是它在第一行崩溃了let dataDecoded: NSData = NSData(base64Encoded: photo.imageData, options: .ignoreUnknownCharacters)! //crash here
let decodedimage = UIImage(data: dataDecoded as Data)
self.test.image = decodedimage
我究竟做错了什么?如何将
UIImage
作为Base64String
存储为bytea
的PostgreSQL
? 最佳答案
所以我要做的是在编码时删除此行
let imageStr: String = dataDecoded.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
并将
PostgreSQL
字段更改为text
而不是bytea