防止错误的多个数据库条目

时间:2018-07-03 01:17:47

标签: node.js forms express upload formidable

我正在处理一个上传脚本,该脚本执行文件上传并在mysql表中添加一个条目。上载工作正常,条目也保存在数据库中,问题是,对于单个上载而言工作正常,但是当我上载多个文件时,将重复mysql表中的记录。

例如:如果我上传3张图片,它将在表格中插入5条以上的记录。我尝试检查for循环是否工作正常,但是循环似乎可以正常运行,还尝试记录查询。

这是代码:

  form.on('file', function(field, file) {

    for(var i =0;i<form.openedFiles.length;i++){
      // var id          = 1;
      var property_id = 1;
      var image       = 'testimage';
      // setTimeout(insert,5000);
      console.log(i);

      var sql = "INSERT INTO `images_tbl`(`property_id`,`property_image`) VALUES ('" + property_id + "','" + image + "')";
      console.log(sql);
      db.query(sql);
      }        

    fs.rename(file.path, path.join(form.uploadDir, file.name));
  });

控制台日志:

Total files3
0
INSERT INTO `images_tbl`(`property_id`,`property_image`) VALUES ('1','testimage')
1
INSERT INTO `images_tbl`(`property_id`,`property_image`) VALUES ('1','testimage')
2
INSERT INTO `images_tbl`(`property_id`,`property_image`) VALUES ('1','testimage')

Ajax呼叫:

$('#upload-input').on('change', function(){

  var files = $(this).get(0).files;

  if (files.length > 0){
    // create a FormData object which will be sent as the data payload in the
    // AJAX request
    var formData = new FormData();

    // loop through all the selected files and add them to the formData object
    for (var i = 0; i < files.length; i++) {
      var file = files[i];

      // add the files to formData object for the data payload
      formData.append('uploads[]', file, file.name);
    }

    $.ajax({
      url: '/upload',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(data){
          console.log('upload successful!\n' + data);
      },
      xhr: function() {
        // create an XMLHttpRequest
        var xhr = new XMLHttpRequest();

        // listen to the 'progress' event
        xhr.upload.addEventListener('progress', function(evt) {

          if (evt.lengthComputable) {
            // calculate the percentage of upload completed
            var percentComplete = evt.loaded / evt.total;
            percentComplete = parseInt(percentComplete * 100);

            // update the Bootstrap progress bar with the new percentage
            $('.progress-bar').text(percentComplete + '%');
            $('.progress-bar').width(percentComplete + '%');

            // once the upload reaches 100%, set the progress bar text to done
            if (percentComplete === 100) {
              $('.progress-bar').html('Done');
            }

          }

        }, false);

        return xhr;
      }
    });

0 个答案:

没有答案