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
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:
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".