0

我正在尝试通过 RestAPI(使用 npm 和 pg-promise)将我的 ios 应用程序(swift)连接到 postgres 数据库

发布字符串和整数值就像一个魅力,但我无法将图像发布到数据库

我正在将图像解码为 base64 字符串,因此我可以将其发送到 POST 请求,然后将字符串发布到我的表中或在发布之前将其解码为 bytea ......这两种方法都适用于一些图片,但无法适用于其他图片我的“格式不正确”错误...

这是我的代码

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);
    });
}

现在,这种方法可以完美地处理这张图片以及更多内容,但无法处理这张图片和更多内容。知道为什么吗?我注意到如果图片超过几百千字节,post方法就会失败......这可能吗?为什么?有没有办法解决这个问题?

注意:所有图片都是jpg格式,所以格式不是问题

4

1 回答 1

0

您编码和/或将数据传递到服务中的方式一定有问题。


我拍了你有问题的照片,顺便说一句,这是一张漂亮的照片,将其保存在本地,然后使用此处解释的直接方法将其插入数据库。

图片插入没有任何问题。

这是完整的应用程序:

var fs = require('fs');

let pgp = require('pg-promise')();

let db = pgp("postgres://postgres@localhost:5433/newone");

fs.readFile('c:/temp/Bella.jpg', function (err, imgData) {
    db.one('insert into images(img) values($1) returning id', imgData, i=>i.id)
        .then(id=> {
            console.info(id);
        })
        .catch(err=> {
            console.error(err);
        });
});

输出新记录 ID:1

我使用的表:

create table images (
    id serial primary key,
    img bytea not null
);

读回数据并保存它会产生相同的有效图片。


您需要调查在前往服务的途中图像数据在哪里损坏;)您的某些图像序列化似乎可能会破坏数据。

并且由于问题表现为大图像,我建议将校验和附加到图像数据,因此更容易找出数据损坏的步骤;)

于 2016-08-20T15:33:12.903 回答