我所要做的只是让用户选择照片,将其上传到服务器上然后解码并显示它。我现在正在做的是编码图像,然后将其作为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]
}
datamapper方法
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
存储?
答案 0 :(得分:1)
所以我要做的就是在编码时删除这一行
let imageStr: String = dataDecoded.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
并将PostgreSQL
字段更改为text
而不是bytea