picture "undefined" with multer - javascript

im trying to get a picture uploaded using multer, here is my server side
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
cb(null, `${file.originalname}`)
}
})
const upload = multer({storage: storage});
app.post('/upload', upload.single("pic"), function (req, res) {
console.log(req.file)
res.send('File uploaded!')
})
in my post method my req.file is undefined
this is my client side
<form action="/upload" method="post">
<input type="file" id="files" style="visibility: hidden;" name = "pic" accept="image/*">
<br>
<label for="files" id="files" class = "lbl">Select file</label>
<br>
<br>
<input type="submit" value="Upload" name="submit" id = "submit">
</form>
if anyone can send a solution it would be amazing.
thanks you.

I found that multer().single(...) fills req.file only if the content type is multipart/form-data:
<form action="/upload" method="post" enctype="multipart/form-data">

Related

upload multiple images from multiple form field or multiple input type in node js

<form action="/profile" method="post" enctype="multipart/form-data">
<input type="file" name="img1" />
<input type="file" name="img2" />
<input type="file" name="img3" />
</form>
How can i upload all the images from different form field in node js
Here is form...
<form action="/profile" method="post" enctype="multipart/form-data">
<input type="file" name="img1" />
<input type="file" name="img2" />
<input type="file" name="img3" />
</form>
You need to install multer npm package for file upload
npm i --save multer
After you need to require this package
const multer = require('multer')
var cpUpload = upload.fields([{ name: 'img1', maxCount: 1 }, { name: 'img2', maxCount: 1 }, { name: 'img3', maxCount: 1 }])
app.post('/profile', cpUpload, function (req, res, next) {
// req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
//
// e.g.
// req.files['img1'][0] -> File
// req.files['img2'] -> Array
//
// req.body will contain the text fields, if there were any
})

POST method from form returns null

I'm trying to use post with express and bodyparser to insert data into MYSQL from a form in a ejs file. It keeps returning null, so it seems that my data is not parsed from the form to my backend.
Could you please help?
Here is my server.js
app.use(express.json({ limit: '100mb' }));
app.use(express.urlencoded({ limit: '100mb', extended: false }));
dotenv.config();
// Set the default views directory to html folder
app.set('views', path.join(__dirname, 'html'));
// Set the folder for css & java scripts
app.use(express.static(path.join(__dirname,'css')));
app.use(express.static(path.join(__dirname, 'node_modules')));
// Set the view engine to ejs
app.set('view engine', 'ejs');
app.use('/', routes);
app.listen(3000, () => {
console.log(`Server is running at ${process.env.SERVER_PORT}`);
});
my index.js
router.post('/save', (req, res) => {
const formData = { username : req.body.username, account : req.body.account, email : req.body.email,
address : req.body.address, start_date : req.body.start_date, picture : req.body.picture,
request : req.body.request };
const sqlPut = "INSERT INTO dbTable ?";
const query = dbconn.conn.query(sqlPut, formData, (err, results) => {
if(err) throw err;
res.redirect('/about')
})
})
Here is my ejs file with the form.
<div class="container" >
<form id="contact" action="/save" method="post">
<h3>New scholar form</h3>
<fieldset>
<input placeholder="username" id="username" type="text" tabindex="1" required autofocus>
</fieldset>
<fieldset>
<input placeholder="account" id="account" type="text" tabindex="2" required>
</fieldset>
<fieldset>
<input placeholder="email" id="email" type="email" tabindex="3" required>
</fieldset>
<fieldset>
<input placeholder="bnc_address" id="bnc_address" type="text" tabindex="4" required>
</fieldset>
<fieldset>
Scholar start date <input placeholder="start_date" type="date" tabindex="4" required>
</fieldset>
<fieldset>
<input placeholder="picture" id="picture" type="text" tabindex="4" required>
</fieldset>
<fieldset>
<textarea placeholder="Scholar request..." id="request" tabindex="5" required></textarea>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit">Submit</button>
</fieldset>
</form>
I can retrieve data from the database and post it just fine. I just haven't figured this one out.
I haven't posted here in a while, so bear with me
You need to change this line:
app.use(express.urlencoded({ limit: '100mb', extended: true }));
Parses the text as URL encoded data(which is how browsers tend to send form data from regular forms set to POST) and exposes the resulting object (containing the keys and values) on req.body.
I imported body-parser without using it. After I removed the import it started working.
Removed this, even though it was not used, it started working after:
const bodyParser = require("body-parser");

Multer with Node.js not working

Okay, here is my form:
<form action="/measure" method="post">
<input type="file" name="thisfile"/>
<input type="submit" value="Give us that file!"/>
</form>
And my server:
var express = require("express"),
multer = require('multer'),
app = express(),
upload = multer({ dest: "./uploads/" });
app.post("/measure", upload.single("thisfile"), function (req, res) {
console.log(req.file);
//other stuff
});
When I submit the form to my server, req.file is undefined.
Wow, wrote you code from scratch assuming a few things but I found the error. In the Multer documentation, it says that Multer will not process a form that is not multipart. So you have to add that to your form (enctype="multipart/form-data"):
<form action="/measure" method="post" enctype="multipart/form-data">
<input type="file" name="thisfile"/>
<input type="submit" value="Give us that file!"/>
</form>
With that it should work. Let me know if this helped you.
PS: Here is the documentation: https://www.npmjs.com/package/multer

sails:Can't able to get textbox value while submitting a form with enctype="multipart/form-data"

I'm doing file upload in sails.js facing issue while submitting a form with enctype="multipart/form-data".
my file.ejs
<form id="uploadForm" enctype="multipart/form-data" action="/Employee/upload"
method="post">
<input type="file" name="uploadFile" />
<input type="text" name="Name" />
<input type="submit" value="submit"/>
</form>
my controller
upload: function (req, res) {
var UserName =req.param("Name");
console.log(UserName);
var uploadFile = req.file('uploadFile');
console.log(uploadFile);
uploadFile.upload(function onUploadComplete (err, files) {
if (err) return res.serverError(err);
console.log(files);
res.json({status:200,file:files});
});
}
I'm going to do create function in this same upload function for storing file name and UserName into DatabaseTable.but req.param("Name") always shows undefined.How can i get texbox value from this form.
I'm new to this sails.js.So please give any suggestions or sollutions for this bug.It will be very usefull for me.

Sails.js : post text input and a file in the same time

I want to send a file and a hidden input text in a form.
<form method="POST" action="/api/import_xlsx_data" enctype="multipart/form-data">
<input type="file" name="xlsx_file_to_import" accept=".xlsx" required>
<input id="url" type="HIDDEN" name="url" value="url-value">
<input type="submit" value="Envoyer">
In my controller request.body is equal to {}.
When I remove enctype="multipart/form-data" it works for my text but not for my file.
To upload my file :
uploadFile.upload({saveAs : fileName, dirname : directoryName},function onUploadComplete(err, files) { ...............});
My controller :
importXLS: function (req, res) {
var uploadFile = req.file('xlsx_file_to_import');
//console.log(req.params()); -> send error params is not a function
console.log(req.body); // send me {}
console.log(req.param('url')); //send me undefined
...... }
More code on pastbin :
My view : view
My controller : controller
Using skipper as a body parser, you must send the text parameters before your file input.
Try this:
<form method="POST" action="/api/import_xlsx_data" enctype="multipart/form-data">
<input id="url" type="HIDDEN" name="url" value="url-value">
<input type="file" name="xlsx_file_to_import" accept=".xlsx" required>
<input type="submit" value="Envoyer">
For more information, please see the documentation for skipper : https://github.com/balderdashy/skipper#text-parameters
To retrieve your field, you need to use :
request.param("url")
And your file with
var file = request.file("xlsx_file_to_import");

Categories