如何使用猫鼬通过multer上传文件?

How to get files uploaded via multer using mongoose?

我正在使用以下函数获取 multer 在 mongodb.The 请求中上传的文件,返回空数组。

exports.getPhotos = async (req, res) => {

    const photos = await Photo.find()
        .then(photos => {
            res.status(200).json(photos);
        })
        .catch(err => res.status(500).json({message: "Something went wrong"}));
};

这是图像的架构。有没有办法在不指定架构的情况下获取文件?


const mongoose = require("mongoose");
const {ObjectId} = mongoose.Schema;

const photoSchema = new mongoose.Schema({
    lenght: {
        type: String,
    },
    chunkSize: {
        type: String,
        required: true
    },
    uploadDate: {
        type: Date,
    },
    filename: {
        type: String,
    },
    md5: {
        type: String,
    },
    contentType: {
        type: String,
    },

});

module.exports = mongoose.model("Photo", photoSchema);

我使用 gridfs,因此它也可以上传更大的文件。下面的一段示例代码

//Connecting to mongo 
const conn = mongoose.createConnection(mongoURI);

//Init gfs 
let gfs; 
conn.once('open', ()=>{
    gfs = GridFsStream(conn.db, mongoose.mongo);
    gfs.collection('uploads');
})
//Creating Storage engine 
const storage = new GridFsStorage({
    url:mongoURI,
    file: (req, file) => {
        return new Promise((resolve, reject)=>{
            crypto.randomBytes(16,(err, buf)=>{
                if(err){
                    return reject(err)
                }
                const fileName = buf.toString('hex') + path.extname(file.originalname)
                //bucket name should match the collection name 
                const fileInfo = {
                    filename:fileName,
                    bucketName:'uploads'
                }
                resolve(fileInfo);
            })
        })
    }
})
const upload = multer({storage})

现在在您的路径中使用此上传常量,如下所示,有几种上传方法,例如数组、单个和...取决于您上传的文件数量。 'uploadedFile' 参数是文件输入的名称,您应该考虑在前端设置它。

app.post('/',upload.single('uploadedFile'),(req, res)=>{
    res.json('file uploaded')
})

此上传中间件会向您的请求添加一个文件,您可以使用该文件将文件名放入数据库中,然后通过该唯一名称使用如下所示的路径获取它。

app.get('/:filename', (req, res)=>{
    gfs.files.findOne({filename:req.params.filename},(err,file)=>{
        if(!file || file.length === 0){
            return res.status(404).json({
                err:'No file Exists'
            })
        }
            const readStream = gfs.createReadStream(file.filename);
            readStream.pipe(res)
    })
})