Error: ENOENT: no such file or directory Multer - node.js

I am getting an error in my application when I want to upload an image with Multer. I already tried to change the name and the loading address but still did not achieve anything. Any ideas ?
This is the code:
const multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb){
cb(null, path.join(__dirname,'../views/upload'));
},
filename: function(req, file, cb){
cb(null, file.fieldname + Date.now());
}
})
var upload = multer({
storage: storage
})
Route:
router.post('/user/change/image', upload.single('image'), isAuthenticated, (req, res) =>{
const file = req.file.image
if(!file) {
req.flash('error', 'Porfavor introduce un archivo valido')
} else {
res.send(file)
res.redirect('/user')
}
})
Form EJS:
<div class="tarjetaedit col-sm-6">
<form method="POST" action="/user/change/image" role="form" enctype="multipart/form-data">
<div class="form-group">
<legend class="legend">Imágen de perfil</legend>
<input type="file" class="form-control" name="image" accept="image/*">
</div>
<div class="form-group">
<button type="submit" class="btn btn-success btn-block">Subir foto</button>
</div>
</form>
</div>
Thanks to all ! I really need to fix this <3

Related

How to check if file is being uploaded with multer

I am uploading a file using multer but the problem is as I am trying to check if it's being uploaded or not using if (req.body.file) the app will not crash but the browser will say that the page is not available. Is there another way of checking if the file will be uploaded?
var multer = require('multer');
var storage = multer.diskStorage({
//multers disk storage settings
destination: function (req, file, cb) {
cb(null, 'public/uploads/')
},
filename: function (req, file, cb) {
//var datetimestamp = Date.now();
cb(null, file.originalname)
}
});
var upload = multer({
storage: storage
})
router.post('/adduser', upload.single('image'), function (req, res) {
console.log(req.body.name);
var data = {
name: req.body.name,
password: req.body.password,
image: 'uploads/' + req.file.originalname
}
users.insert(data, function (err, data) {
console.log(data);
res.redirect('/home');
});
});
<form action="/adduser" method="post" enctype="multipart/form-data">
<input type="text" name="name" />
<input type="password" name="password" />
<input type="file" name="image" />
<input type="submit">
</form>

Node js Multer file upload with extra text input fields

I am trying to upload a file to disk using multer. Here is my code:
const multer = require('multer');
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, __basedir + '/uploads/')
},
filename: (req, file, cb) => {
cb(null, file.fieldname + "-" + Date.now() + "-" + file.originalname)
}
});
var upload = multer({storage: storage});
And here goes my form to collect the file and some extra input fields
<form method="post" enctype="multipart/form-data" action="/uploadfile">
<input name="cate" type="hidden" value="<%= category %>" id="cate" name="cate"></input>
<br>
<input type="file" name="uploadfile" class="btn-success" value="Select Source">
<input type="submit" class="btn-success" ><i class="fas fa-plus"></i> Add a new Source</input>
This function uploads public/img/bg.jpg to my database, thou i would like the file to be picked by the user. How can i get the filepath string in req.files object
fs.createReadStream('public/img/bg.jpg')
.pipe(fileUpload.createWriteStream())
.on('error', function(err) {
console.log("fail");})
.on('finish', function() {
console.log("success");
});
});

req.file in multer always returns undefined

My code below
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const path = require("path");
const bodyParser = require("body-parser");
Below is the config for the multer.
const multer = require("multer");
const upload = multer({ dest: 'uploads/'});
Edit:1.
Also tried this configuration instead of the direct upload variable.But this doesnt work either.
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./uploads/");
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString() + file.originalname);
}
});
const fileFilter = (req, file, cb) => {
if (file.mimetype === "image/jpeg" || file.mimetype === "/image/png") {
cb(null, true);
} else {
cb(null, false);
}
};
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter: fileFilter
});
Product add form processing.
Here i am processing the form and console.log always returns undefined.
router.post("/productadd", upload.single("image"), (req, res) => {
console.log(req.file);
const newProduct = {
imagePath: "https://source.unsplash.com/random/480*480",
title: req.body.title,
description: req.body.description,
price: req.body.price
};
new Products(newProduct).save().then(product => {
res.redirect("/products");
});
});
Here is my form for the file upload
<form action="/productadd" Method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title" placeholder="Enter the Title">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" id="" cols="30" rows="10" class="form-control" placeholder="Enter the content"></textarea>
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="number" class="form-control" name="price" placeholder="Enter the Price">
</div>
<div class="form-group">
<label for="image">Choose an Image:</label>
<input type="file" class="form-control" name="image" />
</div>
<button class="btn btn-primary btn-sm" type="submit">Submit</button>

Request files is undefined in node.js + Multer

I'm trying to create HTML form for uploading image to server with Node.js. I tried to do it with Formidable and Multer. In Formidable I got my Fields object normally but files object was undefined. In Multer I get my req.body normally but req.file is undefined.
I tried to do same with Formidable and no express and everything worked fine, but same didn't worked with express
here is my backend
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(publicPath));
const upload = multer({ storage: multer.memoryStorage() });
app.post('/fileupload', upload.single('testFile'), (req, res, next) => {
const file = req.file;
if (!file) {
const error = new Error('Please upload a file');
error.httpStatusCode = 400;
return next(error);
}
res.send(file);
});
and my frontend
<form class="upload__form" action="/fileupload" method="POST" enctype="multipart/form-data" >
<input type="file" name="testFile" id="file" accept="image/*">
<label for="file" class="hover">Choose a file <i class="fas fa-upload"></i> </label>
<span id="err_msg"></span>
<div class="tag-input">
<input placeholder="Type tags..." class="input" type="text" name="query"><button class="search" type="submit"><b>Add <i class="fas fa-arrow-right"></i></b></button>
<p class="note">*Seperate with commas <i class="far fa-times-circle hover note-close" ></i></p>
</div>
</form>
The code above is with multer, but I also tried with Formidale, nothing changed
I tried your code and it works perfectly, what you could try is not to use a middleware instead of using a function to know if your code is returning an exception.
const upload = multer({ storage: multer.memoryStorage() }).single('testFile');
app.post('/fileupload', (req, res, next) => {
upload(req, res, function (err) {
if (err || !req.file) {
// An error occurred while loading the image.
const error = new Error('Please upload a file')
error.httpStatusCode = 400;
return next(error);
}
res.send(req.file);
});
});
This way you could check if req.file is undefined or if it brings an error in the variable err.

node.js multi file upload not working

<form action="http://localhost:3000/examples" method="post" enctype="multipart/form-data" accept="application/json">
<input type="text" name ="name">
<input type="text" name ="codedescription">
<input type="file" name ="file">
<input type="submit" value="Upload selected file to server">
</form>
var multer = require('multer');
app.use(multer({ dest: './uploads/',
onFileUploadStart : function(file){
console.log('File recieved:');
console.log(file);
},
onFileUploadData:function (file,data){
console.log('Data recieved');
},
onParseEnd: function(req,next){
next();
}
}));
app.route('/examples').post(users.requiresLogin, examples.create);
exports.create = function(req, res) {
console.log("req.files"+req.files);
console.log("req.name"+req.body.name);
console.log("req.codedescription"+req.body.codedescription);
};
Submit form without enctype="multipart/form-data" is working but I can not get files.
Submit form with enctype="multipart/form-data" is working but I can not get files as well as data.
you can try this
<html>
<head>
<title>FileUpload</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<form id = "uploadForm"
enctype = "multipart/form-data"
action = "http://localhost:3000/api/photo"
method = "post"
>
<input type="file" name="userPhoto" multiple />
<input type="submit" value="Upload Image" name="submit" id="btnUpload">
<span id="spnStatus" />
</form>
<script>
$(document).ready(function(){
$('#btnUpload').click(function(){
$('#spnStatus').empty().text("File is Uploading");
$(this).ajaxSubmit({
error : function(xhr){
status('Error : '+xhr.status);
}
success : function(response){
$('#spnStatus').empty().text(xhr);
}
});
});
});
</script>
</body>
</html>
NodeJS Express
var express = require("../node_modules/express");
var multer = require('../node_modules/multer');
var bodyParser = require("../node_modules/body-parser");
var app = express();
app.use(bodyParser.json());
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage }).array('userPhoto',8);
app.get('/',function(req,res){
res.sendFile(__dirname + "/fileUpload.html");
});
app.post('/api/photo',function(req,res){
upload(req,res,function(err) {
if(err) {
console.log(err);
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
app.listen(3001,function(){
console.log("Working on port 3001");
});
Now you can upload upto 8 files at a time, if you want to upload more than eight, just edit var upload = multer({ storage : storage }).array('userPhoto','LIMITHERE');
#karthik comment, i think you need this as well including after jquery, when you want to use his example:
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>

Resources