I am trying to connect my ios app (swift) to a postgres database through RestAPI (using npm and pg-promise)
Posting string and integer values worked like a charm, but I am having trouble posting images to the database
I am decoding the image into base64 string so I can send it to a POST request, and then posting the string into my table or decoding it to bytea before posting... both methods worked with some pictures and failed to work with other pictures giving me "not the correct format" error...
Here is my code
ios Swift
private static func request(todo: JSON -> ()) {
let imageb = UIImageJPEGRepresentation(image, 0.7)
let str64 = Helper.nsdataToStr64(imageb)
Alamofire.request(.POST,
"http://127.0.0.1:3000/api/photos",
parameters: ["visit_id": 1, "photo" : str64])
.responseJSON { (response) in
switch response.result {
case .Success:
let results: JSON = JSON(data: response.data!)["data"]
todo(results)
case .Failure(let error):
print("Failed: \(error)")
}
}
}
queries.js
function uploadPhoto(req, res, next) {
req.body.visit_id = parseInt(req.body.visit_id);
//db.one('insert into photos(visit_id, photo) values(${visit_id}, decode(${photo}, \'base64\')) returning _id',
// req.body)
db.one('insert into photos(visit_id, base64) values(${visit_id}, ${photo}) returning _id',
req.body)
.then(function (data) {
res.status(200)
.json({
status: 'success',
data: data,
message: 'Inserted one photo'
});
})
.catch(function (err) {
return next(err);
//console.log("ERROR:", err.message || err);
});
}
now, this method works flawlessly with this picture and many more but fails with this picture and many more.. Any idea why? I noticed that if the picture is more than a few hundred kilobytes, the post method fails... Is this possible? and why? is there a way to solve this problem?
Note: all the pictures are of jpg format, so the format is not the problem