Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

javascript - multer - req.file always undefined

I've looked at a lot of answer for this same question, but I haven't found a working solution yet. I am trying to make a web app that you can upload files to using express and multer, and I am having a problem that no files are being uploaded and req.file is always undefined.

My code below

'use strict';

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

var app = express();
require('dotenv').load();

app.use(express.static(path.join(__dirname, 'main')));

app.post('/upload', upload.single('upl'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
  console.log(req.file);
  res.status(204).end();
})

var port = process.env.PORT || 8080;
app.listen(port,  function () {
    console.log('Node.js listening on port ' + port + '...');
});

The form

    <form class="uploadForm" action="/upload" method="post" enctype="multipart/formdata">
        <label class="control-label">Select File</label>
        <input name="upl" id="input-1" type="file" class="file">
        <input type="submit" value="submit" />
    </form>

Help very much appreciated, this is driving me crazy.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In case of postman, try following:

  1. Close the postman tab for the API
  2. Open a new tab again
  3. Rebuild the API request and then send.

This may fix the problem. Every time you restart the server you need to do above steps for calling the API again. The reason being multer sends back some cookies called connect.sid to the client which it may require in further communication. Using old cookies will not upload the file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...