简体   繁体   English

节点js multer文件上传无效。 req.file和req.files始终未定义

[英]node js multer file upload not working. req.file and req.files always undefined

I am trying to upload a file to my server, but req.file and req.files is always undefined on my POST REST endpoint. 我试图将文件上传到服务器,但是req.filereq.files始终在我的POST REST端点上未定义。

The content I'm trying to upload is a ".dat" file, and I am expecting a json response. 我要上传的内容是一个“ .dat”文件,并且我希望得到json响应。

Here's my code: 这是我的代码:

Server side: 服务器端:

var express = require('express');
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

var app = express()

app.post('/creoUpload', upload.single('uploadFileField'), function(req, res, next) {
  console.log("req.file = ",JSON.stringify(req.file)); //is undefined
  console.log("req.files = ",JSON.stringify(req.files)); //also undefined
});

Client Side: 客户端:

<form id="creoUploadForm" action="/creoUpload" enctype="multipart/form-data" method="post">
    <input type='file' name='uploadFileField'><br><br>
    <input type='submit' value='Upload'/>
</form>

JS: JS:

$( "#creoUploadForm" ).submit(function( event ) {
    event.preventDefault();
    var formData = new FormData($(this)[0]);
    $.ajax({
          url: '/creoUpload',
          type: 'POST',
          data: formData,
          async: true,
          cache: false,
          contentType: false,
          processData: false,
          success: function (returndata) {
              console.log("RETURN DATA IS: ",returndata);
          },
          error: function (err) {
              console.log("ERROR: ",err);
          }
    });
});

I keep playing around with the fields but it's not working.. anyone see what I'm doing wrong here? 我一直在和田野一起玩,但是没有用..有人看到我在做什么错吗?

I'm following the example from https://www.npmjs.com/package/multer 我正在从https://www.npmjs.com/package/multer跟踪示例

Versions: 版本:

  • Express Version: 4.12.0 速成版:4.12.0
  • Node Version: 6.5.0 节点版本:6.5.0
  • JQuery: 1.12.1 jQuery的:1.12.1

Thank you! 谢谢!

I have the same issue, if you check the documentation on the Error Handling section there is another kind of implementation, that's the one that works for me. 我也有同样的问题,如果您查看“ 错误处理”部分的文档,那么还有另一种实现,那就是对我有用的实现。 The code will be something like this: 该代码将是这样的:

var express = require('express');
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
var app = express();

app.post('/creoUpload', function(req, res, next) {
  upload(req, res, function (err) {
    if (err) {
      // An error occurred when uploading
      console.log('Err: ', err);
      return;
    } else {
       console.log('req.file: ', JSON.stringify(req.file));  
       console.log('req.files: ', JSON.stringify(req.files));
       return;
    }
  })
});

If the req.file and req.files are undefined , then the problem is that multer did not receive the uploaded file and this issue seems related to jQuery . 如果req.filereq.files undefined ,则问题是multer未收到上传的文件,并且此问题似乎与jQuery有关。

Uploading a FormData with jQuery 'v1.12.1' is not supported and it won't send anything at all. 不支持使用jQuery'v1.12.1'上传FormData, 并且完全不会发送任何内容。 I will recommend to try with fetch Api or change the version of your jQuery to 3.3.1 . 我建议尝试获取 Api或将jQuery的版本更改为3.3.1

I already tested the code and I have successfully upload a file to my server when I change my jQuery version from v1.12.1 to v3.3.1 . 我已经测试了代码,并且在将jQuery版本从v1.12.1更改v3.3.1时,已经成功将文件上传到服务器。

You are using multer as a middleware, So before entering into your function and printing it has uploaded images to storage and removes record from req.files . 您正在使用multer作为中间件,因此在进入功能并进行打印之前,已将图像上传到存储中并从req.files中删除了记录。

There are two ways you can access req.files. 您可以通过两种方式访问​​req.files。

  1. Use multer as a function stated by finw3 . 使用multer作为finw3声明的函数

  2. Another solution is: 另一个解决方案是:

//CODE STARTS //代码开始

var storage = multer.diskStorage({

  destination: function (req, file, cb) {

    cb(null, '/filepath')
  },


  filename: function (req, file, cb) {

    let filename = 'filenametogive';
     req.body.file = filename

    cb(null, filename)
  }
})

var upload = multer({ storage: storage })

//CODE ENDS //代码结尾

Now you can access files in req.body.file 现在您可以访问req.body.file中的文件

不要将contentType设置为false ,因为POST方法需要contentType = 'w-xxx-form-urlencoded' ,这是JQ的默认设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM