在文件上传之前快速JS + Multer查询数据库

时间:2015-04-07 17:09:10

标签: javascript mysql node.js multer

我使用Node.JS + Express.JS + Multer来处理文件上传。问题是我需要查询数据库以查看过去是否已上传具有此名称的文件。如果尚未上传,则应该接受。否则,不应接受该文件。我试图使用onFileUploadStart函数使其工作;但是,数据库查询是异步的,我认为没有办法返回false,因为查询的结果出现在回调中。如果有一种同步执行查询的方法,我的目标很容易实现。这是代码:

var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
  //connection details
});

router.post('/upload', multer({
  onFileUploadStart: function(file, req, res) {
    var queryString = "SELECT count(fileName) as count FROM table WHERE fileName = ?;",
      queryInserts = [file.originalname];

    queryString = mysql.format(queryString, queryInserts);

    connection.query(queryString, function(err, rows) {
      if (err) {
        // handle error
      } else {
        if (rows[0].count > 0) {
          // file should not be accepted
        } else {
          // file should be accepted
        }
      }
    });
  },
  dest: "./uploads/"
}), function(req, res) {
  // do other stuff
});

我将非常感谢任何关于如何实现这一目标的想法。感谢。

1 个答案:

答案 0 :(得分:0)

我的快速反应是使用承诺。您可以让onFileUploadStart处理程序创建延迟,将其承诺分配给活动请求对象并处理解析或拒绝承诺。然后在上传路径的主处理程序中,您可以使用then。

我相信这基本上是应用于当前代码的新代码。我注意到我使用的是Q promises library,但还有其他选项(如果您使用的话,也会在ES6中内置承诺)。

var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var Q = requires('q');
var connection = mysql.createConnection({
  //connection details
});

router.post('/upload', multer({
  onFileUploadStart: function(file, req, res) {
    var deferred = Q.defer();
    req.fileUploadPromise = deferred.promise;
    var queryString = "SELECT count(fileName) as count FROM table WHERE fileName = ?;",
      queryInserts = [file.originalname];

    queryString = mysql.format(queryString, queryInserts);

    connection.query(queryString, function(err, rows) {
      if (err) {
        // handle error
        deferred.reject('You had an error...');
      } else {
        if (rows[0].count > 0) {
          // file should not be accepted
          deferred.reject('You had a duplicate file');
        } else {
          deferred.resolve(file); // ?? or something useful
          // file should be accepted
        }
      }
    });
  },
  dest: "./uploads/"
}), function(req, res) {

  req.fileUploadPromise
  .then(function(successResult){
       // do other stuff         
     res.status(200).send('success');
  })
  .catch(function(errorResult){
     // read the error result to provide correct code & error message for user
  })
 .done();
});