how to upload a file in nodejs - node.js

HTML code:-
<html>
<body>
<form action="http://localhost:3000/api" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
</body>
</html>
The code in nodeJS is
app.post('/api',function (req, res) {
//JSON.stringify(req.files);
console.log(JSON.stringify(req.files));
var file = req.files.file;
var stream = fs.createReadStream(file.path);
});
I want to print the details of the-files.
I am getting error
TypeError: Cannot read property 'file' of undefined
at /Users/mAddy/Desktop/check1/server.js:27:25

Use multer, as express/connect no longer supports multipart on its own. Also, use the post method on the express/connect app.
After installing multer:
var multer = require('multer');
var upload = multer({dest:'uploads/'});
app.post('/api', upload.single('file'), function (req, res) {
res.sendStatus(200);
});

Related

TypeError: Cannot read property 'name' of undefined node js

I have the file submission form on the index.html file. When the file selected, i need to say 'file uploaded', else need to display 'please upload the file'
app.js
const express = require("express");
const app = express();
const http = require("http").Server(app).listen(3000);
app.use(express.urlencoded());
app.use(express.json());
console.log("Server Started");
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
}
)
app.post("/", function (req, res) {
if (req.files) {
console.log(req.files);
const file = req.files.filename;
const filename = file.name;
if (!filename) {
res.send("Please select the file to upload");
}
else {
res.send("uploaded");
}
}
})
index.html
<div>
<h1 style="align-content: center">Upload your file here!</h1>
</div>
<div >
<form label="upload" method="post" enctype="multipart/form-data" action="/">
<label> Enter reference</label>
<input type="text" name="test_text"></input>
<br><br>
<input type="file" name="filename">
<input type="submit" value="upload">
</form>
</div>
Error message:
TypeError: Cannot read property 'name' of undefined
at C:\Users\Desktop\LocalGithub\uploadFileLocal-express-fileupload\app.js:24:27
The following is quoted from express docs:
In Express 4, req.files is no longer available on the req object by default. To access uploaded files on the req.files object, use multipart-handling middleware like busboy, multer, formidable, multiparty, connect-multiparty, or pez.
As it said, I suggest you to use multer since it's more popular and easy to use
EDIT:
If you are using "express-fileupload" middleware, you have to load it via .use() method:
const express = require("express");
const app = express();
const http = require("http").Server(app).listen(3000);
const fileUpload = require('express-fileupload');
^^^^^
app.use(express.urlencoded());
app.use(express.json());
app.use(fileUpload({
^^^
useTempFiles : true,
tempFileDir : '/tmp/'
}));
...
check the docs for more details:
Please try replace file.name with req.files[0].originalname.
You did not create the object for which attribute name is defined.
object: req.files.filename, attribute: req.files.filename.name should work fine.
Your code should be like this:
app.post("/", function (req, res) {
if (req.files.filename) { //missing filename
console.log(req.files.filename); //missing filename
const file = req.files.filename;
const filename = file.name;
...
});

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.

Nodejs + Expressjs : Pass value in POST with Uploading of file

I am new in node. I just want to pass value in POST request with something like uploading of file. here is my sample code:
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var multer = require('multer');
var upload = multer({ dest: '/tmp/'});
app.use(express.static('public'));
app.post('/process_post', urlencodedParser, function (req, res) {
console.log(req.files.file.name);
var file = __dirname + "/" + req.files.file.name;
fs.readFile( req.files.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'Save successfully',
first_name:req.body.firstname,
last_name:req.body.lastname,
filename:req.files.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
HTML:
<html>
<body>
<form action="http://127.0.0.1:8081/process_post" method="POST" enctype="multipart/form-data">
First Name: <input type="text" name="firstname">
<br>
Last Name: <input type="text" name="lastname">
<br>
Picture: <input type="file" name="file" size="50" />
<br>
<input type="submit" value="Submit">
</form>
</body></html>
The req.files is always undefine.
Thanks in advance!
You're requireing multer, but never configuring or using it. from the docs:
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
})

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>

File upload to a Node JS server

I am trying to upload a file to my node js server using express.
Here is my nodejs code:
var express=require('express');
var app=express();
var fs=require('fs');
var sys=require('sys');
app.listen(8080);
app.get('/',function(req,res){
fs.readFile('upload.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");
});
});
});
My upload.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>
I am getting an error that the req.files is undefined.
What could be wrong? The file upload is also not working.
As noted in the docs, req.files, along with req.body are provided by the bodyParser middleware. You can add the middleware like this:
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());

Resources