欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

gridfs-stream 文件上传至Mongodb并访问

程序员文章站 2022-06-22 11:21:15
1.安装依赖cnpm install gridfs-stream --save2.实现文件上传至Mongodbvar mongoose = require('mongoose');const Grid = require('gridfs-stream');const fs = require('fs');const utils = require('../resource/utils');const jwt = require('jsonwebtoken');const confi...

1.安装依赖

cnpm install gridfs-stream --save

2.实现文件上传至Mongodb

var mongoose = require('mongoose');
const Grid = require('gridfs-stream');
const fs = require('fs');
const utils = require('../resource/utils');
const jwt = require('jsonwebtoken');
const config = require('../config');
Grid.mongo = mongoose.mongo;

//文件上传至 mongodb
async function uploadFile(ctx) {
    try {
        var conn = mongoose.connection;
        var gfs = Grid(conn.db);
        //filename 文件名称,我这里是自定义的文件名称,为了保证同名文件不冲突。使用的用户ID加4位随机数加时间戳
        let writeStream = gfs.createWriteStream({ filename: jwt.verify(ctx.headers.authorization, config.encrypt.JWT_SECRET) + "_" + utils.generateProductId() + ctx.request.files.file.name.toString().toLowerCase().substr(ctx.request.files.file.name.toString().length - 4) })
        // GridFSBucket 方式上传
        // const girdFSBucket = new mongoose.mongo.GridFSBucket(conn.db)
        // var writeStream = girdFSBucket.openUploadStream(jwt.verify(ctx.headers.authorization, config.encrypt.JWT_SECRET) + "_" + utils.generateProductId() + ctx.request.files.file.name.toString().toLowerCase().substr(ctx.request.files.file.name.toString().length - 4))
        var result = fs.createReadStream(ctx.request.files.file.path).pipe(writeStream);
        // console.log(result)
        ctx.body = result.options
    } catch (error) {
        console.log(error)
        throw error;
    }
}

module.exports = {
    uploadFile
}

gridfs-stream 文件上传至Mongodb并访问

3.访问Mongodb上的文件(返回base64)

var mongoose = require('mongoose');
const Grid = require('gridfs-stream');
const fs = require('fs');
const utils = require('../resource/utils');
const jwt = require('jsonwebtoken');
const config = require('../config');
Grid.mongo = mongoose.mongo;

//访问mongodb 图片,返回base64 访问方式
async function findFiles(ctx) {
    try {
        var imgs_Base64 = await finds(ctx.params.filename);
        // console.log(imgs_Base64);
        ctx.body = imgs_Base64;
        logger.info("Request! method:" + ctx.method + ",request url:" + ctx.url + ",Base64:" + imgs_Base64);
    } catch (error) {
        console.log(error)
        throw error;
    }
}

function finds(filename) {
    try {
        return new Promise((resolv, reject) => {
            var conn = mongoose.connection;
            var gfs = Grid(conn.db);
            gfs.files.find({ filename: filename }).toArray((err, files) => {
                // console.log(files)
                let data = [];
                let readstream = gfs.createReadStream({
                    filename: files[0].filename
                });
                readstream.on('data', (chunk) => {
                    data.push(chunk);
                });
                readstream.on('end', () => {
                    data = Buffer.concat(data);
                    let img = 'data:image/png;base64,' + Buffer.from(data).toString('base64');
                    // console.log(img)
                    resolv(img)
                    // console.log("sent", files[0].filename);
                });
            })
        })
    } catch (error) {
        throw error;
    }
}

module.exports = {
    findFiles
}

4.下载Mongodb中的文件

async function download(ctx) {
    var conn = mongoose.connection;
    var gfs = Grid(conn.db);
    //./aaa.jpg 是下载文件的目录位置。
    var fsWrite = fs.createWriteStream('./aaa.jpg');
    var readstream = gfs.createReadStream({
        filename: ctx.params.filename
    })
    readstream.pipe(fsWrite)
}
module.exports = {
    download
}

5.删除mongodb中的文件

async function deleteFile(ctx) {
    var conn = mongoose.connection;
    var gfs = Grid(conn.db);
    //可以使用 文件名称,和ID  例如:{filename:''}或{_id:''}
    gfs.remove({ filename: ctx.params.filename }, (err, res) => {
        console.log(err);
        console.log(res);
    })
}

module.exports = {
    deleteFile
}

6. 判断文件是否存在

async function existFile(ctx){
    var conn = mongoose.connection;
    var gfs = Grid(conn.db);
    gfs.exist({ filename: ctx.params.filename }, (err, res) => {
        console.log(err);
        console.log(res);
    })
}

 

本文地址:https://blog.csdn.net/qq_42172829/article/details/109237557