How can i upload a picture with nodejs and express? - javascript

I have a CMS for a food automation system and I'm going to add a part for upload pictures for foods:
<form method="post" enctype="multipart/form-data" action="/upload">
<td><input class="styleFormForAddProducts foodpicForAddFood" type="file" name="file"></td>
<td><input class="styleFormForAddProducts submitForAddFood" type="submit" value="Submit" ></td>
</form>
I wrote this code for making a POST request in Express.js:
app.post('/upload', function (req, res) {
var tempPath = req.files.file.path,
targetPath = path.resolve('./uploads/image.png');
if (path.extname(req.files.file.name).toLowerCase() === '.png') {
fs.rename(tempPath, targetPath, function(err) {
if (err)
throw err;
console.log("Upload completed!");
});
} else {
fs.unlink(tempPath, function () {
if (err)
throw err;
console.error("Only .png files are allowed!");
});
}
});
However when I define this app.use, I get an error:
Middleware: app.use(express.bodyParser({uploadDir:'/img'}));
Error: Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
When I define a middleware like this :
app.use(bodyParser({uploadDir:'/img/'}));
I don't have any errors but my code doesn't work correctly .

This solution worked for me :
multer = require('multer'),
upload = multer({ dest: 'views/img' });
app.post('/upload',upload.single('file'), function (req, res) {
});
And my form HTML form :
<form method="post" enctype="multipart/form-data" action="/upload">
<input class="styleFormForAddProducts foodpicForAddFood" type="file" name="file">
<input class="styleFormForAddProducts submitForAddFood" type="submit" value="Submit" >
</form>

Related

Unexpected behaviour of Multer and Express when field name is wrong

const express = require('express');
const multer = require('multer');
const uuid = require('uuid');
const server = express();
server.use(express.static('client/'));
const upload = multer({
storage: multer.diskStorage({
destination: function (req, file, callback) {
callback(null, 'temp/upload/');
},
filename: function (req, file, callback) {
callback(null, uuid.v4().concat('.').concat(file.mimetype.split('/')[1]));
}
}),
fileFilter: function (req, file, callback) {
const whitelist = ['image/jpeg', 'image/png'];
if (whitelist.includes(file.mimetype)) {
callback(null, true);
} else {
callback(null, false);
}
},
}).single('image');
server.post('/api/dummy', (req, res) => {
upload(req, res, async function (error) {
if (error || req.file === undefined) return res.sendStatus(400);
// Doing something, if there is no error.
})
});
server.listen(80);
As you can see, multer expects a file with field name image. Now, if I send a file with correct field name, it gives expected result both from browser and Thunderclient.
Now, I tried to change the field name of the file to anything other than image. Still, Thunderclient works, giving expected result. But browser not getting any response for big images i.e. - 7MB. But surprisingly getting expected result in browser too if the file size is relatively low i.e. - 250KB.
This is the client.
<!DOCTYPE html>
<html>
<body>
<form action="/api/dummy" method="post" enctype="multipart/form-data">
<label for="name">Name</label>
<input type="text" name="name" id="name">
<br>
<label for="logo">Logo</label>
<input type="file" name="logo" id="logo">
<br>
<input type="submit" value="submit">
</form>
</body>
</html>
I have tried with this two random images -
with this image, the browser did not get any response but
with this image, the browser did get the response back.

How do I continuously update the progress of a file upload on the frontend in NodeJS/Express

I have a form for a multi-file upload on an EJS frontend and I am looking for a way of updating a span with an id of "progressSpan" to show the current progress in % of the file that is being uploaded.
The Frontend form looks like the following:
<form method="POST" action="/upload" enctype="multipart/form-data" id="uploadForm">
<label>Select Files</label>
<input type="file" name="fileUpload" id="realFileinput" multiple>
<button type="submit" id="submit-upload-btn" class="uploadFormBtns">Start Uploading</button>
<span id="progressSpan>0%</span>
</form>
The function responsible for handling the upload on the backend has been written using multer, altough if something like express-fileupload would be suited better for the progress tracking, then changing it would'nt be a big deal. In the codesnippet below, fileData is an array of JSON objects containing a name and a fileSize, which is handeled by an in this case irrelevant function in the frontend. Depending on the outcome (success/error) it prints the index.ejs file with the according message
router.post('/upload', (req, res) => {
upload(req, res, (err) => {
if (err) {
//render error
res.render('index', { msg: err, fileData });
} else {
req.files.forEach(file => {
fileData.push({
name: file.filename,
fileSize: convertDataUnit(dir, file.filename)
});
});
res.render("index", { msg: "Upload successful!", fileData });
}
});
});

files not uploading sails js

So, when I upload file it doesn't me show any error, it just doesn't upload the file and I get the message '0 files uploaded successfully, I do get the record in database for each uploaded item
So, here's the input form
<form action='./make' method="post">
<input type="file" name="vid"> <br>
<input type="text" name="name"> <br>
<input type="hidden" name="_csrf" value="<%= _csrf %>">
<input type="hidden" name="ownerID" value="<%= req.session.User.id %>">
<input type="submit" value="add video">
</form>
And this is the 'make' action:
make: function (req, res, next) {
Video.create(req.params.all(), function videoCreated (err,video) {
console.log("create video");
// if(err) return next(err);
req.file('vid').upload({
dirname: './assets/images'
}, function (err, uploadedFiles) {
if (err) return res.negotiate(err);
return res.json({
message: uploadedFiles.length + ' file(s) uploaded successfully!'
});
});
if(err){
console.log(err);
req.session.flash = {
err: err
}
return res.redirect('/user/new');
}
});
}
Try with this:
index.ejs
<form enctype="multipart/form-data" action="epale" method="post">
<input type="file" id="archivo" name="archivo">
<input type="submit" value="Enviar">
</form>
IndexController.js
epale: function (req, res) {
//return res.send('Hi there!');
if (req.method === 'GET')
return res.json({ 'status': 'GET not allowed' });
// Call to /upload via GET is error
var uploadFile = req.file('archivo');
console.log(uploadFile);
uploadFile.upload({
dirname: '../../assets/images',
saveAs: function(file, cb) {
cb(null, file.filename);
}
}, function onUploadComplete(err, files) {
// Files will be uploaded to .tmp/uploads
if (err) return res.serverError(err);
// IF ERROR Return and send 500 error with error
console.log(files);
res.json({ status: 200, file: files });
});
},
routes.js
'/': {
view: 'homepage'
},
'/index': {
view: 'index'
},
'/epale': {
controller: "Index",
action: "epale",
},
Revised (05-11-2016) in: http://maangalabs.com/blog/2014/08/12/uploading-a-file-in-sails/

File upload using Multipart fails in nodejs

I'm trying to upload a file in node js using multipart where I get Cannot POST error? I'm totally new to node js. So can you help me what I'm doing wrong
My Code?
HTML
<form id = "uploadForm"
enctype = "multipart/form-data"
action = "/api/uploadfile"
method = "post">
<input type="file" name="fileUpload"/>
<input type="submit" value="Upload File" name="submit">
</form>
Server.js
var express = require('express');
var app = express();
var multer = require('multer');
app.use(express.static(__dirname));
app.get('/', function(request, response){
response.sendFile("./index.html");
});
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}).single('fileUpload');
app.post('/api/uploadfile',function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
app.listen(8080);
console.log("App listening on port 8080");
Error message as follows :
Error uploading file
i tried your code,its working here.The reason may be,
1)you missed out the closing of form tag
<html>
<form id = "uploadForm"
enctype = "multipart/form-data"
action = "/api/uploadfile"
method = "post"
>
<input type="file" name="fileupload" />
<input type="submit" value="Upload file" name="submit">
</form>
</html>
2)make sure that you have a folder named -> uploads

Upload files with node.js

I have this code in order to upload files with node.js:
app.use(express.bodyParser());
// or, as `req.files` is only provided by the multipart middleware, you could
// add just that if you're not concerned with parsing non-multipart uploads,
// like:
app.use(express.multipart());
app.get('/',function(req,res){
fs.readFile('uploadHTML.html',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
});
});
app.post('/upload',function(req,res)
{
console.log(req.files);
fs.readFile(req.files.displayImage.path, function (err, data) {
// ...
var newPath = __dirname;
fs.writeFile(newPath, data, function (err) {
res.redirect("back");
});
});
});
Here is the HTML file:
<html>
<head>
<title>Upload Example</title>
</head>
<body>
<form id="uploadForm"
enctype="multipart/form-data"
action="/upload"
method="post">
<input type="file" id="userPhotoInput" name="displayImage" />
<input type="submit" value="Submit">
</form>
<span id="status" />
<img id="uploadedImage" />
</body>
</html>
When I upload the file, it gives me the next error:
TypeError: Cannot read property 'displayImage' of undefined at c:\NodeInstall\nodejs\express.js:42:22 at callbacks (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:164:37) at param (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:138:11) at pass (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:145:5) at Router._dispatch (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:173:5) at Object.router (c:\NodeInstall\nodejs\node_modules\express\lib\router\index.js:33:10) at next (c:\NodeInstall\nodejs\node_modules\express\node_modules\connect\lib\proto.js:193:15) at Object.expressInit [as handle] (c:\NodeInstall\nodejs\node_modules\express\lib\middleware.js:30:5) at next (c:\NodeInstall\nodejs\node_modules\express\node_modules\connect\lib\proto.js:193:15) at Object.query [as handle] (c:\NodeInstall\nodejs\node_modules\express\node_modules\connect\lib\middleware\query.js:45:5)
What could be the reason?
I do recommend you to use awesome module https://github.com/domharrington/fileupload for handling file uploads in node/express.
var fileupload = require('fileupload').createFileUpload('/uploadDir').middleware
app.post('/upload', fileupload, function(req, res) {
// files are now in the req.body object along with other form fields
// files also get moved to the uploadDir specified
})
Another way to upload files could be using something like this
Jade template
form.data(action='/user/register', method='post', class="long-fields", enctype='multipart/form-data')
input(type="text" name="name")
input(name='fileLogo', type='file')
input(type="submit" value="Register")
Controller
formidable = require('formidable'); //file upload handling via form
uuid = require('node-uuid'); //Unique ID
path = require('path'); //Path compiler
fs = require('fs'); //FileSystem
var form = new formidable.IncomingForm();
form.keepExtensions = false;
form.maxFieldsSize = 2 * 1024 * 1024; //2mb
form.parse(req, function(err, fields, files) {
console.log(fields);
console.log(files);
fs.readFile(files.fileLogo.path, function (err, data) {
var pathNew = __dirname + '/../../uploads/' + uuid.v1() + path.extname(files.fileLogo.name)
fs.writeFile(pathNew, data, function (err) {
console.log('uploaded', pathNew);
});
});
res.send(jade.renderFile( settings.pathLess + prefix + '/register.jade', {
req : req
}));
});

Categories

Resources