正在上传图片

时间:2017-07-26 09:29:11

标签: node.js ajax express image-uploading multer

HTML code:

<form  enctype="multipart/form-data">
   <input id="upFile" class="upFile" type="file"
    size="0" name="file" accept="image/gif,image/jpeg,image/png">
   <input type="submit" id="upFileBtn" class="upFile">
</form>

Ajax代码:结果:成功

$('#upFileBtn').click(function () {
    var file = $('#upFile');
    var formData = new FormData();
    formData.append('file',file[0]);
    $.ajax({
        url: '/api/upload',
        type: 'post',
        data: formData,
        // async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function(data){
            if(200 === data.code) {
                $('#upFile').val('');
                alert('success');
            } else {
                alert("failed");
            }

        },
        error: function(){
            alert("wrong");
        }
    });
});

API:

var express = require('express');
var router = express.Ro
router();var multer  = require('multer');
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, config.upload)// upload:"./public/uploads"
   },
    filename: function (req, file, cb) {
      cb(null,file.originalname)
   }
});

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


//upload
router.post('/upload', upload.single('file'), function (req, res, next) {
console.log(req.file);//undefined
});

我无法找出问题所在。我希望req.file存在,但事实并非如此。 我找到了目录('public/uploads'),但它没有任何图片。 Ajax代码已经运行警报('成功'),我想multer没有保存图像或没有得到图像。但我看到网络请求已发送图像。那么谁能告诉我它有什么问题?

1 个答案:

答案 0 :(得分:0)

您的API服务器示例无效,我认为它只是工作服务器的一部分。我将发布最小的API服务器示例

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

app.use('/', express.static(__dirname));

var storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, './files');// upload:"./public/uploads"
  },
  filename: function(req, file, cb) {
    cb(null, file.originalname)
  }
});

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

//upload
app.post('/api/upload', upload.single('file'), function(req, res, next) {
  console.log(req.file);//undefined
  res.send({code: 200});
});

app.listen(3000, function() {
  console.log('Example app listening on port 3000!')
});

主要问题在这里

var file = $('#upFile');
var formData = new FormData();
formData.append('file',file[0]);

我已使用var formData = new FormData($('form')[0]);

在请求中发送了一个文件

这是一个工作示例

<html>
<head>
  <script
      src="https://code.jquery.com/jquery-3.2.1.js"
      integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
      crossorigin="anonymous"></script>
</head>
<body>
<form enctype="multipart/form-data">
  <input id="upFile" class="upFile" type="file"
         size="0" name="file" accept="image/gif,image/jpeg,image/png">
  <input type="submit" id="upFileBtn" class="upFile">
</form>
<script>
  $('#upFileBtn').click(function() {
    var formData = new FormData($('form')[0]);
    $.ajax({
      url: '/api/upload',
      type: 'post',
      data: formData,
      // async: false,
      cache: false,
      contentType: false,
      processData: false,
      success: function(data) {
        if (200 === data.code) {
          $('#upFile').val('');
          alert('success');
        } else {
          alert("failed");
        }

      },
      error: function() {
        alert("wrong");
      }
    });
  });
</script>

</body>
</html>