【问题标题】:Spring Data MongoDB GridFS images are corrupted when getting with contentType使用 contentType 获取 Spring Data MongoDB GridFS 图像时已损坏
【发布时间】:2014-10-19 13:51:49
【问题描述】:

我正在尝试使用 Spring 使用 GridF 存储和检索图像。

上传方法1:

public void savePicture(InputStream photo, Customer customer) {

        Query query = new Query (Criteria.where("filename").is(customer.getId()).and("metadata.status").is("active"));

        Update update = new Update().set("metadata.status" , "false");

        WriteResult wr = this.mongoTemplate.updateFirst(query, update, "fs.files");

        if (!wr.getLastConcern().callGetLastError()){

        DBObject metaData = new BasicDBObject();
        metaData.put("status", "active");

        String imageFormat = this.imageUtils.getImageFormat(photo);

        String contentType = "image/" + imageFormat;

        GridFSFile gridFsFile = this.gridFsTemplate.store(photo, customer.getId(), contentType, metaData);

        }

    }

上传方法2(仅在调用this.gridFsTemplage.store时不同)

public void saveProfilePicture(InputStream photo, Customer customer) {

        Query query = new Query (Criteria.where("filename").is(customer.getId()).and("metadata.status").is("active"));

        Update update = new Update().set("metadata.status" , "false");

        WriteResult wr = this.mongoTemplate.updateFirst(query, update, "fs.files");

        if (!wr.getLastConcern().callGetLastError()){

        DBObject metaData = new BasicDBObject();
        metaData.put("status", "active");

        GridFSFile gridFsFile = this.gridFsTemplate.store(photo, customer.getId(), metaData);

        }

    }

下载方法:

public InputStream getPicture(Customer customer){

        Query query = new Query(Criteria.where("filename").is(customer.getId()).and("metadata.status").is("active"));

        GridFSDBFile gridFsDBFile = this.gridFsTemplate.findOne(query);

        return gridFsDBFile.getInputStream();

    }

在 MongoDB/GridFS 上上传工作和写入的两种方法,但是当我使用方法 1 时,我无法下载图片并且它似乎已损坏。例如,如果我上传一张 7.8KB 的图片,下载的版本是 500 字节 (7.3KB),我无法使用图像查看器打开它。 当我使用方法 2 上传时,一切正常。

有什么想法吗?

【问题讨论】:

    标签: java spring mongodb spring-data gridfs


    【解决方案1】:

    如果你在 MongoShell 上运行它,你可以看到 gridfs 文件:db.fs.files.find() 现在,方法 1 中的问题是您没有指定文件的全名。(如果 您没有指定全名,即文件名+扩展名)

    GridFSFile gridFsFile = this.gridFsTemplate.store(photo, customer.getId(), contentType, metaData);
    Should be changed to=>
    GridFSFile gridFsFile = this.gridFsTemplate.store(photo, customer.getId() + "." + imageFormat, contentType, metaData);
    

    【讨论】:

    • 但是在这种情况下,当我查询数据库时,我怎么知道文件扩展名是什么? (我假设我当然可以存储不同的图像格式)
    • 没错,如果您想存储不同格式的图像,请使用方法 2.. :)
    • :) 好的,但在这种情况下,我无法填写 contentType 字段,我认为在我的情况下(至少现在)并不严格需要该字段,但我认为我无法填写它很奇怪:-/
    • 正确,方法 2 适合您的用例。希望代码技巧有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 2017-06-23
    • 1970-01-01
    • 2014-03-21
    • 2016-04-26
    相关资源
    最近更新 更多