2

我在将文件同时上传到 pc 和 DB 时遇到问题。

我在我的代码中使用了两个不同的模块

  • Multer:用于将文件从前端上传到 PC
  • CSV-to-JSON:用于将 CSV 文件转换为 json 以便将该文件存储在数据库中。

但是,使用两个单独的函数根本不是我的意图。因此,当我尝试将这两个模块与基本代码结合起来时,使用Multer上传文件可以工作,但我想将该文件上传到 MongoDB,这需要通过csv-to-json解决,这对我来说似乎没有任何问题。

这是我的代码:

var express = require('express');
var multer = require('multer');
const csv = require('csvtojson');
// Import Mongodb
const mongoClient = require('mongodb').MongoClient,
  assert = require('assert');

var filename = null;

var storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function(req, file, cb) {
    filename = Date.now() + '-' + file.originalname;
    cb(null, filename)
    console.log(filename);
  }
})

var upload = multer({
  storage: storage
})

var app = express();

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

app.post('/', upload.single('file-to-upload'), function(req, res, next) {

  // Mongodb Connection URL 
  const url = 'mongodb://localhost:27017/csvfilereader';

  // Use connect method to connect to the Server
  mongoClient.connect(url, (err, db) => {
    assert.equal(null, err);

    if (db) {
      console.log("Connected correctly to server");

      insertDocuments(db, function() {
        db.close();
      });
    } else {
      console.log('\n', 'Problem with connection', err)
    }

  });

  const insertDocuments = (db, callback) => {
    // Get the documents collection
    let collection = db.collection('uploaded');

    // CSV File Path
    const csvFilePath = 'uploads/' + filename;

    console.log(csvFilePath);
    /**
     * Read csv file and save every row of
     * data on mongodb database
     */
    csv()
      .fromFile(csvFilePath)
      .on('json', (jsonObj) => {
        collection.insert(jsonObj, (err, result) => {
          if (err) {
            console.log(err);
          } else {
            console.log('suceess');
            res.redirect('/');
            filename = null;
          }
        });
      })
      .on('done', (error) => {
        console.log('end')
      })
  }

});

app.listen(3200);
<!--
HTML Code that runs on Root
-->

<html lang="en">
  <head>
    <title>Simple Multer Upload Example</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <form action="/" enctype="multipart/form-data" method="post">
      <input type="file" name="file-to-upload">
      <input type="submit" value="Upload">
    </form>  
  </body>
</html>

4

1 回答 1

0

您需要通过 multer 传递的请求访问文件名。您的文件名变量不指向任何对象。

req.file.filename将允许访问您已由 multer 上传的文件。

更新代码:

var express = require("express");
var multer = require("multer");
const csv = require("csvtojson");
// Import Mongodb
const MongoClient = require("mongodb").MongoClient,
    assert = require("assert");

var filename = null;

var storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, "uploads/");
    },
    filename: function(req, file, cb) {
        filename = Date.now() + "-" + file.originalname;
        cb(null, filename);
    },
});

var upload = multer({
    storage: storage,
});

var app = express();

app.get("/", (req, res) => {
    res.sendFile(__dirname + "/index.html");
});

app.post("/", upload.single("file-to-upload"), function(req, res, next) {
    // Connection URL
    const url = "mongodb://localhost:27017";
    console.log("Multer", req.file.filename);
    // Database Name
    const dbName = "csvreader";

    // Create a new MongoClient
    const client = new MongoClient(url, { useNewUrlParser: true });

    // Use connect method to connect to the Server
    client.connect(function(err) {
        assert.equal(null, err);
        console.log("Connected successfully to database");

        const db = client.db(dbName);
        insertDocuments(db, function() {
            console.log("Closing connection");
            client.close();
        });
    });

    const insertDocuments = (db, callback) => {
        // Get the documents collection
        const collection = db.collection("uploaded");

        // CSV File Path
        const csvFilePath = "uploads/" + filename;

        console.log("Reading file from ", csvFilePath);
        /**
         * Read csv file and save every row of
         * data on mongodb database
         */
        csv()
            .fromFile(csvFilePath)
            .then(jsonObj => {
                console.log(jsonObj);
                collection.insert(jsonObj, (err, result) => {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log("suceess");
                        res.redirect("/");
                        filename = null;
                        callback();
                    }
                });
            })
            .catch(err => {
                //error reading file
                console.log(err);
            });
    };
});

app.listen(3200, () => {
    console.log("Server working at port 3200");
});
于 2019-02-27T14:19:34.637 回答