如何使用express / multer上传文件而不重定向

时间:2017-12-03 20:21:45

标签: javascript ajax express multer

注意:我发现了this帖子,但我没有找到帮助,其他帖子与角度/反应有关,我没有使用。

我有一个文件上传应该发送一个文件类型正确的响应。文件上传工作正常,但我的页面重定向到文件所在的位置。我希望页面在它所在的同一页面上相同。

home.ejs:

<!-- upload video -->
<form method="post" action="/upload" class="custom-file" enctype="multipart/form-data">
  <input type="file" name="video-file" class="custom-file-input" />
  <span class="custom-file-control"></span>

  <!-- optional dropdown to specify number of cores -->
  <div class="dropdown">
    <button class="btn btn-secondary dropdown-toggle" 
            type="button" 
            id="dropdownMenuButton" 
            data-toggle="dropdown" 
            aria-haspopup="true" 
            aria-expanded="false"
            name="number-of-cores">
      Use all Cores
    </button>
    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
      <a class="dropdown-item">Use all Cores</a>
      <a class="dropdown-item">Use one Core</a>
    </div>
  </div>

  <!-- upload button -->
  <input class="btn btn-primary upload-btn" type="submit" id="upload-btn" value="Upload">

这就是我希望页面不重定向的原因;因此,如果文件格式正确,页面可以显示。

$('body').on('click', '#upload-btn', function (event) {
      $.ajax({
          type: 'POST',
          url: '/',
          dataType : "application/json; charset=utf-8",
          contentType: JSON.stringify(false),
          success: function (response) { 
              $("#errorMessage").html("* file successfully opened");
              console.log('successfully uploaded', response);
          },
          error: function (result) {
              $("#errorMessage").html("* Incorrect file/no file given");
              console.log('coudn\'t upload');
          }
      });
      //return false;
  })

server.js

const express = require('express');
const multer = require('multer');
var path = require('path')

const app = express();

app.set('view engine', 'ejs');
app.set('views', './views');
app.use(express.static('public'));

function fileFilter (req, file, cb) {
    if (path.extname(file.originalname) !== '.mp4') {
        return cb(null, false);
    }

    cb(null, true);
}

const upload = multer({ dest: 'uploads/', fileFilter:fileFilter});

app.get('/', (req, res) => {
    res.render('home', { testGreeting: 'Hello world' });
});

app.post('/upload', upload.single('video-file'), function(req, res) {
    console.log(req.file);
    console.log(req.params);
    if (req.file) {
        console.log("successfully received");
        res.send({success: "success"});
    }
    return res.end();
});

app.listen(3000, () => console.log('Listening on Port 3000.'));

这可能不是主题,但我的ajax代码总是运行错误,而不是成功。如果我也能得到这方面的帮助,我将不胜感激。 谢谢!

更新:event.preventDefault()是解决方案:

$('body').on('click', '#upload-btn', function (event) {
      event.preventDefault();
      $.ajax({
              ... //same as before
      });
      return false;
})

1 个答案:

答案 0 :(得分:0)

您需要在客户端阻止event.preventDefault()的默认浏览器操作。您可以详细了解preventDefault here