使用相同的 POST 请求将文件上传到 MongoDB 和本地服务器

Upload file to MongoDB and to a local server with the same POST request

我正在尝试创建自己的上传服务,我希望能够在我的服务器上的本地文件夹中以及在我的 mongoDB 云服务 (Atlas) 上上传文件。

到目前为止,我已经分别完成了这两项服务并且它们工作正常(我制作了一个用于将文件上传到 mongo Atlas 的 Node 应用程序和另一个用于将文件上传到服务器的 Node 应用程序)。但是现在,我想将这两个统一到一个节点应用程序中,在每个 POST 请求之后,文件都会发送到 Atlas 和本地文件夹。我正在使用 multer 和 gridfs。

第一次尝试是在我的 index.html 文件上创建两个 "file-input" 字段,每个字段都有两个不同的 POST 请求:一个发送到 '/upload'文件到 Atlas,第二个文件到“/uploaddisk”,它将文件发送到磁盘。但是,第二个 post 请求不起作用(每次我想提交文件时都会抛出错误)。将文件上传到 mongoDB 似乎每次都能正常工作。

关于如何在单个 POST 上执行此操作的任何想法?提前致谢!

这是我为 server.js 应用编写的代码:

//mongo DATA
const dbURI =
    "myc-atlas-credentials";
mongoose.Promise = global.Promise;
// mongoose.connect(bdURI, { useNewUrlParser: true, useUnifiedTopology: true });
const conn = mongoose.createConnection(dbURI, {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

//init gfs
let gfs;

conn.once("open", () => {
    //initialize the stream
    gfs = Grid(conn.db, mongoose.mongo);
    gfs.collection("uploads");
});

//creating the storage engine for MONGO
const storage = new GridFsStorage({
    url: dbURI,
    file: (req, file) => {
        return new Promise((resolve, reject) => {
            const filename = file.fieldname + '-' + Date.now() + path.extname(file.originalname);
            const fileInfo = {
                filename: filename,
                bucketName: "uploads"
            };
            resolve(fileInfo);
        });
    }
});
const upload = multer({ storage: storage });

//set storage engine with multer for disk
const diskstorage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, path.join(__dirname + '/uploads/'));
    },
    filename: function(req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});
const diskupload = multer({ storage: diskstorage });

//route for POST - upload data to mongo
app.post('/upload', upload.single('file'), (req, res) => {
    console.log({ file: req.file });
    // res.json({ file: req.file });
    res.redirect('/');
});

//route for POST - upload data to disk
app.post('/uploaddisk', diskupload.single('file'), (req, res, next) => {
    const file = { file: req.file };
    if (!file) {
        const error = new Error('Please upload a file');
        error.httpStatusCode = 400;
        return next(error);
    }
    res.redirect('/');
});


你可以这样试试:

function fileUpload(req, res, next) {
  upload.single('file')(req, res, next);
  diskupload.single('file')(req, res, next);
  next();
}

//route for POST - upload data to mongo
app.post('/upload', fileUpload, (req, res) => {
    console.log({ file: req.file });
    // res.json({ file: req.file });
    res.redirect('/');
});