I am using multer to save the file on server developed through express & nodejs.
I am usign following code.
var express = require('express'),
multer = require('multer')
var app = express()
app.get('/', function(req, res){
res.send('hello world');
});
app.post('/upload',[ multer({ dest: './uploads/'}), function(req, res){
res.status(204).end()
}]);
app.listen(3000);
Multer saves the file for me in the specified destination folder.
All this is working fine but I have following questions:
If the file saving fails for various reasons, it looks like my route will always return status 204.
I am not sure if status 204 is retured after file is saved or while the file is getting saved asynchronously, status 204 is returned.
This is how to write multer middleware that handle upload and errors
const multer = require("multer");
function uploadFile(req, res, next) {
const upload = multer().single('yourFileNameHere');
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
// A Multer error occurred when uploading.
} else if (err) {
// An unknown error occurred when uploading.
}
// Everything went fine.
next()
})
}
You can handle errors using the onError option:
app.post('/upload',[
multer({
dest : './uploads/',
onError : function(err, next) {
console.log('error', err);
next(err);
}
}),
function(req, res) {
res.status(204).end();
}
]);
If you call next(err), your route handler (generating the 204) will be skipped and the error will be handled by Express.
I think (not 100% sure as it depends on how multer is implemented) that your route handler will be called when the file is saved. You can use onFileUploadComplete to log a message when the upload is done, and compare that to when your route handler is called.
Looking at the code, multer calls the next middleware/route handler when the file has been uploaded completely.
Try this
var upload = multer().single('avatar')
app.post('/profile', function (req, res) {
upload(req, res, function (err) {
if (err) {
// An error occurred when uploading
return
}
// Everything went fine
})
}
ref :
http://wiki.workassis.com/nodejs-express-get-post-multipart-request-handling-example/
https://www.npmjs.com/package/multer#error-handling
As you can see from the code below (the source from the muter index.js file), if you not pass the onError callback the error will be handled by express.
fileStream.on('error', function(error) {
// trigger "file error" event
if (options.onError) { options.onError(error, next); }
else next(error);
});
Be careful with the system when the user sends anything to you
I usually set more [*option1]:
process.on('uncaughtException', function(ls){
// console.log(ls);
(function(){})();
});
And then:
var upload= multer({ dest: __dirname + '/../uploads/' }).single('photos');
// middle ..
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
// A Multer error occurred when uploading.
console.log('MulterError', err);
} else if (err) {
// An unknown error occurred when uploading.
// Work best when have [*option1]
console.log('UnhandledError', err);
}
if(err) {
return res.sendStatus(403);
}
res.sendStatus(200);
});
package: "multer": "^1.4.2"
var multer = require('multer')
var upload = multer().single('avatar')
app.post('/profile', function (req, res) {
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
handle error
} else if (err) {
handle error
}
else{
write you code
}
})
})
you can see this from the documentation
According to the multer documentation (https://github.com/expressjs/multer#error-handling)
Error handling
When encountering an error, Multer will delegate the error to Express. You can display a nice error page using the standard express way.
If you want to catch errors specifically from Multer, you can call the middleware function by yourself. Also, if you want to catch only the Multer errors, you can use the MulterError class that is attached to the multer object itself (e.g. err instanceof multer.MulterError).
code sample
const multer = require('multer')
const upload = multer().single('avatar')
app.post('/profile', function (req, res) {
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
// A Multer error occurred when uploading.
} else if (err) {
// An unknown error occurred when uploading.
}
// Everything went fine.
})
})
When we re-write the code in this question with latest version of multer (v1.4.5-lts.1)
const express = require('express');
const multer = require('multer');
const app = express();
const upload = multer({ dest: './uploads/' }).single('fieldName');
app.get('/', (req, res) => {
res.send('hello world');
});
app.post(
'/upload',
(req, res, next) => {
upload(req, res, (err) => {
if (err instanceof multer.MulterError) {
res.status(404).send(err + 'Upload failed due to multer error');
} else if (err) {
res.status(404).send(err + 'Upload failed due to unknown error');
}
// Everything went fine.
next();
});
},
(req, res) => {
res.status(204).end();
}
);
app.listen(3000);
To check the Multer errors and non multer errors we can add validations using fileFilter and limits
eg:
I am adding a CSV file filter method and some limits
// CSV file filter - will only accept files with .csv extension
const csvFilter = (req, file, cb) => {
console.log('csv filter working');
if (file.mimetype.includes('csv')) {
cb(null, true);
} else {
cb('Please upload only csv file.', false);
}
};
// adding the csv file checking, file number limit to 1 and file size limit 10 1kb
const upload = multer({
dest: './uploads/',
fileFilter: csvFilter,
limits: { files: 1, fileSize: 1024 }
}).single('fieldName');
We can see different errors are thrown when we try to upload non CSV file or >1kb sized file or multiple files.
I know its late but it might help others.
Here is how I handle errors and use it safely in my express/typescript
project.
const upload = (fieldName: string) => {
return (req: Request, res: Response, next: NextFunction) => {
return multer({
storage: multer.diskStorage({
destination: (req, file, cb) => {
if (file.fieldname === 'post') {
return cb(null, `${path.join(path.dirname(__dirname), 'uploads/postImg')}`);
} else if (file.fieldname === 'profile') {
return cb(null, `${path.join(path.dirname(__dirname), 'uploads/ProfilePic')}`);
} else {
return cb(new Error(`${file.fieldname} is incorrect`), null);
}
},
filename: (req, file, cb) => {
return cb(null, `${file.originalname}-${Date.now()}-${file.fieldname}`);
},
}),
fileFilter: (req, file, cb) => {
const fileExtension = file.mimetype.split('/')[1];
if (!(fileExtension in allowedFiles)) return cb(null, false);
return cb(null, true);
},
dest: `${path.join(path.dirname(__dirname), 'uploads')}`,
limits: {
fileSize: 1024 * 1024 * 3, // 3MB
files: 1,
},
}).single(fieldName)(req, res, (err: any) => {
if (err instanceof multer.MulterError) {
// handle file size error
if (err.code === 'LIMIT_FILE_SIZE') return res.status(400).send({ error: err.message });
// handle unexpected file error
if (err.code === 'LIMIT_UNEXPECTED_FILE') return res.status(400).send({ error: err.message });
// handle unexpected field key error
if (err.code === 'LIMIT_FIELD_KEY') return res.status(400).send({ error: err.message });
}
next();
});
};
};
app.post("/upload", (req: Request, res:Response)=>{
res.json({message:"file uploaded"})
})
Related
I am trying to upload image to to server and store it in a separate folder. I am submitting multipart form with image attached to it but I am not getting any errors, response is always successfull even when I am trying to submit an empty form. Is there are any suggestions why it is not working?
controller.js
const multer = require('multer');
const shortid = require('shortid');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "/home/username/projects/data/img/"); // Static route to save images
console.log("DESTINATION CB: " + cb);
},
filename: function (req, file, cb) {
cb(null, shortid.generate() +".jpg");
}
});
const maxSize = 10 * 1000 * 1000; // 10 MB Max Picture size
var upload = multer({
storage: storage,
limits: { fileSize: maxSize },
fileFilter: function (req, file, cb){
// Set the filetypes, it is optional
var filetypes = /jpeg|jpg|png/;
var mimetype = filetypes.test(file.mimetype);
var extname = filetypes.test(path.extname(file.originalname).toLowerCase());
if (mimetype && extname) {
return cb(null, true);
}
cb("Error: File upload only supports the " + "following filetypes - " + filetypes);
}
}).single('image');
module.exports = {
createBlog: function(req, res, next) {
upload(req, res, function(err) {
if (err instanceof multer.MulterError) {
res.json({status: "Error", error_message: "Some kind of error with image"});
} else {
res.json({status: "Success", success_message: "Image uploaded successfully."});
}
});
}
};
route.js
const express = require('express');
const router = express.Router();
const controller = require('../app/api/controllers/controller');
router.post('/blog/create', controller.createBlog)
module.exports = router;
server.js
const express = require('express');
const logger = require('morgan');
const route = require('./routes/route');
const bodyParser = require('body-parser');
const mongoose = require('./config/database'); // DB configuration
const app = express();
// Connection to mongodb
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));
mongoose.set('useFindAndModify', false);
app.use(bodyParser.json({limit: "50mb"}));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit: 50000}));
app.use('/blogx', route);
app.get('/favicon.ico', function(req, res) {
res.sendStatus(204);
});
// Handle 404 error
app.use(function(req, res, next) {
let err = new Error('Not Found!');
err.status = 404;
next(err);
});
// Handle errors
app.use(function(err, req, res, next) {
console.log(err);
if (err.status === 404) {
res.status(404).json({message: "Not Found!"});
} else {
res.status(500).json({message: "Something looks wrong :("});
}
});
app.listen(3001, function(){
console.log('MAIN Server is listening on port 3001');
});
And this is how I am trying to submit form using Insomnia
request
You probably need to make sure that the upload directory /home/username/projects/data/img/ exists before starting the server/executing the request.
Note that you would have been able to detect this kind of error yourself, if your error logic also had handled non-multer errors, as in this case instead of a multer error a system error (NOENT) is thrown :
upload(req, res, function(err) {
if (err instanceof multer.MulterError) {
res.json({status: "Error", error_message: "Some kind of error with multer"});
} else if(err) {
res.json({status: "Error", error_message: err.message});
} else {
res.json({status: "Success", success_message: "Image uploaded successfully."});
}
});
The below is a rudimentary file upload utility. It handles React / Axios API POSTs satisfactorily. Files get uploaded to the ~uploads folder under root on the server. How does one add API DELETE handling capability to it? Envision a use case where a user uploads an attachment to a blog post and then deletes the attachment from the blog post. Have had issues locating an example.
var cors = require('cors');
var express = require('express');
var multer = require('multer')
var app = express();
app.use(cors());
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
var storage = multer.diskStorage(
{
destination: function (req, file, cb)
{
cb(null, 'fileuploads');
},
filename: function (req, file, cb)
{
cb(null, file.originalname );
}
})
var upload = multer({ storage: storage }).array('file')
app.post('/upload',function(req, res)
{
upload(req, res, function (err)
{
if (err instanceof multer.MulterError)
{
return res.status(500).json(err)
}
else if (err)
{
return res.status(500).json(err)
}
return res.status(200).send(req.file)
})
});
app.listen(8001, function() {
console.log('App running on port 8001');
});
EDIT:
Modified app.delete(...) to the below, which successfully deletes the file but after about a minute throws this error in the console: [Error: ENOENT: no such file or directory, unlink '<PATH VALUE>']
app.delete('/writer/:file_to_delete', async (req, res) =>
{
const path = 'assets/uploads/' + req.params.targetFile;
console.log(path);
try
{
fs.unlink(path)
// NOTE: `fs.unlinkSync(path)` does the same thing
console.log('File deleted!');
return res.status(200);
}
catch(err)
{
console.error(err)
return res.status(500).json(err)
}
});
I found a way forward. The code is below but I'm happy to hear about better ways to do it:
// NOTE: `file_name` values are obfuscated and uniquely generated by the client.
// The actual file name is in data storage.
app.post('/delete/:file_name', (req, res) =>
{
const theFile = 'attachments/' + req.params.file_name;
var resultHandler = function(err) {
if(err) {
console.log("file delete failed", err);
return res.status(500).json(err)
}
console.log("file deleted");
return res.status(200).send({data: req.params.file_name + ' deleted'});
}
fs.unlinkSync(theFile, resultHandler);
});
I've written a react app that makes use of the FilePond file uploader but am having trouble getting multer to accept the request from filepond, it always returns a 500 error.
If I use a standard file upload control the request is accepted by the server and the file uploads fine.
Does anyone have any thoughts on what might be causing this?
Thanks
This is my server.js code:
var express = require('express');
var app = express();
var multer = require('multer')
var cors = require('cors');
app.use(cors())
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' +file.originalname )
}
})
var upload = multer({ storage: storage }).array('file')
app.get('/',function(req,res){
return res.send('Hello Server')
})
app.post('/upload', function(req, res) {
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
return res.status(500).json(err)
// A Multer error occurred when uploading.
} else if (err) {
return res.status(500).json(err)
// An unknown error occurred when uploading.
}
res.send([req.files[0].filename]);
return res.status(200).send(req.file)
// Everything went fine.
})
});
app.listen(8000, function() {
console.log('App running on port 8000');
});
I'm tryng to upload a file and the upload goes ok! The problem is when I try to upload some file that is not accepted according to me fileFitler handling. I would like to receive some error in console or redirect the user to the back page, but I'm just receiving a error on brower : cannot read read property filename of undefined.
But, if I upload some extension that is accepted, goes ok!
Here is my code:
const mongoose = require('mongoose');
const multer = require('multer');
const uuidV4 = require('uuid/v4');
const Video = require('../models/videoModel');
function fileFilter(req, file, cb){
const extension = file.mimetype.split('/')[0];
if(extension !== 'video'){
return cb(null, false), new Error('Something went wrong');
}
cb(null, true);
};
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
const newName = uuidV4();
const extension = file.mimetype.split('/')[1];
cb(null, newName +`.${extension}`);
}
});
var upload = multer({ storage: storage, fileFilter: fileFilter});
exports.uploadVideo = upload.single('file'); // the single param should be the name of the file input form
exports.CreateVideo = (req, res) => {
const newVideo = {title: req.body.title, path: req.file.filename};
Video.create(newVideo, function(err, result){
if(err){
console.log('Não foi possível realizar o upload do vídeo.' + err);
}
else{
console.log('Vídeo upado com sucesso!');
res.redirect('/');
console.log(result);
}
})
};
exports.Home = (req, res) =>{
res.render('index');
};
exports.ShowVideos = (req, res) =>{
Video.find({}, function(err, result){
if(err){
res.redirect('/');
}
else{
res.render('video', {videoData:result});
}
})
};
The get an error on the console, you could change your fileFilter and pass an error to the cb function. See:
function fileFilter(req, file, cb){
const extension = file.mimetype.split('/')[0];
if(extension !== 'video'){
return cb(new Error('Something went wrong'), false);
}
cb(null, true);
};
Hope it helps!!
I have created a node.js server and i use the multer module for upload some files.
my problem is : how can i handle errors? like if the client close untile the upload is finished? sorry for bad english, i'm italian.
this is my actual don't working code :
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/root/appsistMe/public/AppMeFile/Utenti/'+req.session.nome);
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
})
var upload = multer({ storage: storage,
onError : function(err, next) {
console.log('error');
next(err);
}});
app.post('/uploadFile', upload.single('file'), function (req, res, next){
console.log("CI SIAMO AL DOWNLOADDDDDD");
mongo.aggiungiNuovoFile(req, res);
res.status(204).end();
});
onError was removed in version 1.0.0 .
var upload = multer().single('avatar')
app.post('/profile', function (req, res) {
upload(req, res, function (err) {
if (err) {
// An error occurred when uploading
return
}
// Everything went fine
})
})
Please check this link for more details