admin管理员组

文章数量:1415664

I'm trying to integrate express-fileupload to upload and image to my server. I have followed the example provided in this link, express-fileupload Examples but It doesn't work. Below I have included each file involved with only the relevant lines of code.

index.ejs: Relevant lines

<form method="post" action="/images" enctype="multipart/formdata">
    <div class="panel-body form-horizontal">
        <div class="form-group col-md-12">
            <label class="col-sm-2 control-label" for="file">Browse:</label>

            <div class="col-md-10">
                <input class="form-control" type="file" name="file" id="file">
            </div>
        </div>
    </div>
</form>

server.js

const express = require('express');
const config = require('./server/configure');
let app = new express();

app.set('port', process.env.PORT || 3300);

app = config(app);

app.listen(app.get('port'), () => {
    console.log(`Server up: http://localhost:${app.get('port')}`);
});

configure.js

const express = require('express');
const path = require('path');
const expressFileUpload = require('express-fileupload');
const routes = require('./routes');

module.exports = (app) => {

    // applying expressFileUpload middleware
    app.use(expressFileUpload());

    routes(app);

    app.use('/public/', express.static(path.join(__dirname, '../public')));
    return app;
};

routes.js

const image = require('../controllers/image');

module.exports = (app) => {
    app.post('/images', image.create);
};

image.js

module.exports = {

    create(req, res) {
        let image = req.files.file;
    }
}

Error

I get an error at the following line let image = req.files.file; which states,

TypeError: Cannot read property 'file' of undefined

Why is file undefined and how do I correctly upload an image using express-fileunload?

I'm trying to integrate express-fileupload to upload and image to my server. I have followed the example provided in this link, express-fileupload Examples but It doesn't work. Below I have included each file involved with only the relevant lines of code.

index.ejs: Relevant lines

<form method="post" action="/images" enctype="multipart/formdata">
    <div class="panel-body form-horizontal">
        <div class="form-group col-md-12">
            <label class="col-sm-2 control-label" for="file">Browse:</label>

            <div class="col-md-10">
                <input class="form-control" type="file" name="file" id="file">
            </div>
        </div>
    </div>
</form>

server.js

const express = require('express');
const config = require('./server/configure');
let app = new express();

app.set('port', process.env.PORT || 3300);

app = config(app);

app.listen(app.get('port'), () => {
    console.log(`Server up: http://localhost:${app.get('port')}`);
});

configure.js

const express = require('express');
const path = require('path');
const expressFileUpload = require('express-fileupload');
const routes = require('./routes');

module.exports = (app) => {

    // applying expressFileUpload middleware
    app.use(expressFileUpload());

    routes(app);

    app.use('/public/', express.static(path.join(__dirname, '../public')));
    return app;
};

routes.js

const image = require('../controllers/image');

module.exports = (app) => {
    app.post('/images', image.create);
};

image.js

module.exports = {

    create(req, res) {
        let image = req.files.file;
    }
}

Error

I get an error at the following line let image = req.files.file; which states,

TypeError: Cannot read property 'file' of undefined

Why is file undefined and how do I correctly upload an image using express-fileunload?

Share Improve this question edited Jul 1, 2020 at 10:24 Carlo Corradini 3,4553 gold badges22 silver badges28 bronze badges asked Jul 1, 2020 at 7:51 Simple Simple 4377 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

No issue in your node js code.It's working fine.Issue is in your HTML file.

the form enctype must be enctype="multipart/form-data" & not what you added.

Here is the reference: HTML form submit how to: File Upload and email

When working with file upload and express I suggest you to use Multer.

File upload is tricky.

When one or more files "arrive" to the Server you can store them with two different methods:

  1. Save the files to the disk in a known and secure location
  2. Save the files in the RAM memory

Both methods have pro and cons. Is up to you to decide which is better for your needs.

Here is an example from my server that handle the upload of an user profile image (GitHub project link: HERE). It's written in typescript but the syntax is almost the same.

File Middleware - FileMiddleware.ts

Middleware for handling both disk and memory storage. I can choose which one is the best for the specific express route(example under the middleware).

import path from 'path';
import multer from 'multer';

export default class FileMiddleware {
  public static readonly memoryLoader = multer({
    storage: multer.memoryStorage(),
    limits: {
      fileSize: 2097152, // 2 MByte
    },
  });

  public static readonly diskLoader = multer({
    storage: multer.diskStorage({
      destination: (_req, _file, cb) => {
        cb(null, path.join(__dirname, '../tmp/upload'));
      },
    }),
    limits: {
      fileSize: 67108864, // 64 MByte
    },
  });
}

User route - user.ts

User route for handling avatar file upload. You can see I am defining the path, the file middleware (in this case a memory storage - single file identified by image key) and the Controller used to handle the process.

import { Router } from 'express';
import { UserController } from '@app/controller';
import { FileMiddleware } from '@app/middleware';

const router = Router();

router.post(
  '/user/avatar',
  FileMiddleware.memoryLoader.single('image'),
  UserController.updateAvatar
);

export default router;

In the controller you can retrieve the image using req.file, simple as that.

As I said use Multer, the configuration and use is very simple and intuitive.

PS: Remember, using file upload with form implies adding enctype="multipart/form-data".

本文标签: javascriptHow do you use expressfileupload correctlyStack Overflow