How to POST file via jQuery to nodejs connect-busboy - javascript

I can successfully send a file to connect-busboy by using an HTML form's action attribute like so:
<form ref='uploadForm' method="post" action="http://localhost:3000/fileupload" enctype="multipart/form-data" id='uploadForm'>
Select file to upload:
<input type="file" name="sampleFile">
<input type="submit" value="Upload!">
</form>
However, I would prefer to not have my page redirect.
I tried to convert this to jQuery by removing the action attribute in the form tag and adding an onclick function with the following:
$.ajax({
url:'http://localhost:3000/fileupload',
type:'post',
contentType: 'multipart/form-data',
data:$('#uploadForm').serialize(),
success:function(){
alert('Success');
},
error: function() {
alert('Error');
},
});
Unfortunately, this doesn't work with the error:
TypeError: Cannot read property 'end' of undefined
The Nodejs code is as follows:
const express = require('express');
const busboy = require('connect-busboy');
const app = express();
app.use(busboy());
const fs = require('fs');
app.post('/fileupload', function(req, res) {
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
fstream = fs.createWriteStream(__dirname + '/files/' + filen ame);
console.log(fstream);
file.pipe(fstream);
fstream.on('close', function () {
res.send('Success');
});
});
});
var port = process.env.PORT || 3000;
app.listen(port);
Full error: http://i.imgur.com/vUqmjWS.png

By explicitly serializing the form you are implicitly avoiding/removing the multipart/form-data format. Instead, pass a FormData instance as the data. You can instantiate a new FormData from an existing form like:
var data = new FormData($('#uploadForm')[0]);
$.ajax({
url: 'http://localhost:3000/fileupload',
type: 'POST',
contentType: false,
processData: false,
cache: false,
data: data,
success: function() {
alert('Success');
},
error: function() {
alert('Error');
}
});

Related

FormData Defined on Front-End, Undefined on Back-End

I want to upload a picture on change and with formData and I believe it's grabbing the information on the front-end because I don't get undefined, but on my back-end it comes as undefined.
//THIS IS MY INPUT
<input class="second-picture" type="file" name="filename" accept="image/gif, image/jpeg, image/png">
//DEFINING FORMDATA
var formData = new FormData();
formData.append('file', $('input.second-picture').prop('files')[0])
console.log(formData.get("file"))
// THIS CONSOLE GIVES ME:
File {
name: picture.jpg
lastModified: xxx (date)
size: 541092
type: "image/jpeg"
webkitRelativePath: ""
}
Here's the AJAX call and the back-end 'POST'
AJAX CALL -
$.ajax({
type: 'POST',
url: `/api/Upload-second-picture`,
crossDomain: true,
data: formData,
cache: false,
processData: false,
contentType: false,
enctype: 'multipart/form-data',
mimeType: 'multipart/form-data',
beforeSubmit : function() {
},
success : function(responseText, statusText, xhr, $form) {
console.log('responseText', responseText)
}
});
router.post('/Upload-second-picture', function(req, res) {
let upload = multer({ storage: storage }).single('filename')
upload(req, res, function (err) {
let file = req.file
console.log('this is my file', file) // RETURNS UNDEFINED
if(file != undefined) {
if (err) {
return res.send("Error: file not uploaded 2", err)
}
return res.send(fileName)
}
})
})
How can I make the back end grab the information too?
You are putting the file in file key, inside new FormData, So it should be natural that fetch the same with multer:
let upload = multer({ storage: storage }).single('file');//instead of filename

how to download server file in node js?

Could you please tell me how to download server file in node js
here is my code
Node js code (request code)
var express = require('express');
var multer = require('multer');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var path = require('path');
var PORT = process.env.PORT || 3000;
// use of body parser
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(cors());
app.get('/download', function(req, res){
console.log(__dirname);
var file = path.join(__dirname , '/uploads/file-1534458777206.xlsx');
console.log(file)
res.download(file); // Set disposition and send it.
});
app.listen(PORT, () => {
console.log(`App is listening to ${PORT}`);
})
I am requesting like that on client
$('.download').on('click', function () {
$.ajax({
url: 'http://localhost:3000/download',
type: 'GET',
dataType: 'json',
success: function (data) {
console.log('data')
},
error: function (jqXHR, textStatus, errorThrown) {
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
getting error on console
ERRORS: parsererror
3index.html?_ijt=9lu9erpan2oq6qf28851ngj0ra:32 ERRORS: parsererror
2index.html?_ijt=9lu9erpan2oq6qf28851ngj0ra:32 ERRORS: parsererror
server logs
C:\Users\B0207296\WebstormProjects\uploadFile\server
C:\Users\B0207296\WebstormProjects\uploadFile\server\uploads\file-1534458777206.xlsx
why files is not download on client as I mention file is present in above url
To get the file content via ajax:
Just remove the dataType, your file is being parsed to json causing the error.
$('.download').on('click', function () {
$.ajax({
url: 'http://localhost:3000/download',
type: 'GET',
success: function (data) {
console.log(data); // File data
},
error: function (jqXHR, textStatus, errorThrown) {
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
To download the file is better user a virtual link
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<b class="download">Download Here</b>
<script>
$('.download').on('click', function () {
var link = document.createElement('a');
link.href = 'http://localhost:3000/download';
var e = document.createEvent('MouseEvents');
e.initEvent('click', true, true);
link.dispatchEvent(e);
})
</script>
</body>
</html>

Ajax fails when sending a data object to the NodeJs server

when pressing a button this code gets executed
function submitData() {
$.ajax({
type: 'GET',
url: '/questionnaire/submit', // listen to a route
dataType: "json",
data: JSON.stringify({ // some test data
satisfactory: "house",
improvement: "bla",
rating: "this is a text"
})
}).done(function () {
$(location).attr('href', '/sendOff'); // redirect to another route
}).fail(function () {
console.log("Error");
});
}
and the server is listening on this
app.get('/questionnaire/submit', function (req, res) {
var data = req.query; // Get the data object from the Ajax call
console.log(data);
res.send(null); // Send nothing back
});
Whenever pressing the button, "Error" gets logged in the console. The Ajax call always fails.
Even when writing res.send("Success"); the client will log "Error". What am I missing?
Update:
I installed the body parser middleware and use this code now
my app.js
const path = require('path');
const express = require('express');
const exphbs = require('express-handlebars');
const bodyParser = require('body-parser');
const handlebars = exphbs.create({
defaultLayout: 'index',
extname: 'hbs'
});
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
require('./Server/Routes/questionnaire')(app);
require('./Server/Routes/sendOff')(app);
app.engine('hbs', handlebars.engine);
app.set('view engine', 'hbs');
app.use(express.static(path.join(__dirname, 'Public')));
app.listen(8888, function () {
console.log('Server running on port 8888');
});
my route
module.exports = function (app) {
app.get('/questionnaire', function (req, res) {
res.render('questionnaire');
});
app.post('/questionnaire/submit', function (req, res) {
var data = req.body;
console.log(data);
res.send(null);
});
};
and my client function
function submitData() {
$.ajax({
type: 'POST',
url: '/questionnaire/submit',
dataType: "json",
data: JSON.stringify({
satisfactory: $("#edtSatisfactory").val(),
improvement: $("#edtImprovement").val(),
rating: currentRating / ratingElements.length
})
}).done(function () {
$(location).attr('href', '/sendOff');
}).fail(function () {
});
}
And when executing the Ajax call the client still runs into .fail()
Client request is :
function submitData() {
$.ajax({
type: 'POST',
url: '/questionnaire/submit', // listen to a route
dataType: "json",
data: {
satisfactory: "house",
improvement: "bla",
rating: "this is a text"
}
}).done(function () {
$(location).attr('href', '/sendOff'); // redirect to another route
}).fail(function () {
console.log("Error");
});
}
and the server is listening on this Using bodyParser middleware in your node backend
:
app.post('/questionnaire/submit', function (req, res) {
var data = req.body; // Get the data object from the Ajax call
console.log(data);
res.end(); // Send nothing back
});
You're using a GET http method, which shouldn't take body, you should instead append your data to the back of the url. Or if you want to use a body, then switch to a POST.
url: '/questionnaire/submit?satisfactory=house&improvement=bla&rating=sometext
If you're using POST don't forget:
'Content-Type': 'application/json',
Edit: On the server you need to parse the JSON request, this is best done with a middleware called body-parser:
npm install --save body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
This will parse your JSON and add it to req.body.
Try this..
Client Side
function submitData() {
$.ajax({
type: 'POST',
url: '/questionnaire/submit', // listen to a route
'Content-Type': 'application/json',
data: JSON.stringify({"satisfactory": "house", "improvement": "bla", "rating": "this is a text"})
}).done(function () {
console.log('hi')
}).fail(function () {
console.log("Error");
});
}
On server Side:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/questionnaire/submit', function (req, res) {
var data = req.body
console.log(data);
res.send(null); // Send nothing back
});
You have to install body-parser library using following command.
npm install --save body-parser
It will log "Hi" as ajax done is called. BTW You have redirected the page to 'sendOff' in your question.
If you are not understanding anything plz comment below.
You just have to replace
dataType: "json",
with this:
'Content-Type': 'application/json'
in $.ajax request
Hope this will work.. I have tried & tested.

File upload to nodejs using ajax

I am trying to upload image to nodejs server using ajax but it fails to get file.
Client Side
function sendFileToServer(file){
var formData = new FormData();
formData.append('profile_image',file,file.name);
$.ajax({
type: "POST",
url: "URL",
data: formData,
dataType:'json',
processData: false,
success: function (data) {
alert("Data Uploaded: "+data);
},
error : function(err){
alert(JSON.stringify(err));
}
});
}
$("#profile_image_2").change(function(){
var file = this.files[0];
sendFileToServer(file);
});
Server Side
var multer = require('multer');
var mime = require('mime-lib');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/upload/')
},
filename: function (req, file, cb) {
console.log("filename exte "+file.mimetype);
console.log(mime.extension(file.mimetype));
cb(null, Date.now() + '.' + mime.extension(file.mimetype)[0]);
//crypto.pseudoRandomBytes(16, function (err, raw) {
// cb(null, raw.toString('hex') + Date.now() + '.' + mime.extension(file.mimetype));
//});
}
});
var uploading = multer({ storage: storage });
router.post('/profile',uploading.single('profile_image') ,function(req,res){
if (req.file){
res.json("In here");
}else{
res.json("FILE DOES NOT EXIST");//ALWAYS ENDS UP HERE
}
});
When i try it in bare form it works fine, but not using ajax. Please help
Try to use jQuery Form Plugin. It will make this for you.

How to send data from server to client in nodejs?

I'm running a server in nodejs with express to serve an html form within the file index.html to a client like this:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser());
app.get('/', function(req, res){res.sendfile('index.html');});
app.post('/', function(req, res){
res.json(req.body);
});
app.listen(8080);
req.body gives me the form input. Now I need to send back req.body to the client, and to do this I'm using ajax on the client side (inside index.html) like this:
var data;
$('#submit').click(function()
{
console.log('Button Clicked');
$.ajax({
url: '/',
type:'POST',
data: data,
dataType: 'json',
}).done(function(data) {
console.log(data);
});
})
However when I click the button submit I get Object {} in the browser console and not the form input.
What am I missing here?
There are two issues in your code:
First, as the comments mention, bodyParser() is deprecated, you should be using the specific bodyParser middlewares (json, text, urlencoded, raw). So in your case:
app.use(bodyParser.json())
Second, your client side call to jQuery.ajax should stringify your data. Like this:
$('#submit').click(function()
{
console.log('Button Clicked');
$.ajax({
url: '/',
type:'POST',
data: JSON.stringify(data),
dataType: 'json',
}).done(function(data) {
console.log(data);
});
})

Categories