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

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

Related

Can't get JSON data from client side

I want to send JSON data from client side to server side.
Client side:
function send() {
var formData = {
firstname: $("#name").val(),
lastname: $("#lastname").val()
}
console.log("sending: " + JSON.stringify(formData));
$.ajax({
type: "POST",
contentType: "application/json",
url: "/dat",
data: JSON.stringify(formData),
dataType: 'json',
success: function(customer) {
console.log(JSON.stringify(customer));
},
error: function(e) {
alert("Error!")
console.log("ERROR: ", e);
}
});
}
Server side:
app.post("/dat", function (req, res) {
console.log(JSON.stringify(req.body)); // return undefined
res.end(JSON.stringify({ "nine": 9, "ten": 10, "eleven": 11 }));
});
I tried everything, but JSON.stringify(req.body) return only undefined. Sending data from server to client side working just fine...
Any suggestions?
You're resetting app here with:
var app = express();
Remove that line.

post $http request using file type input and get req.body and req.file not using multer nodejs

my tried code is :
//jade
input(type='file', ng-model='filename',file-model='Image', required='')
// controller.js
$scope.reupload = () => {
$scope.user = {
UserName: 'sam',
FirstName: 'sameer',
};
const fd = new FormData();
$scope.theData = {};
fd.append('file', $scope.Image);
$scope.theData.i = fd;
$http({
method: 'POST',
url: '/api/uploadresume',
data: $scope.theData,
})
.then((data) => {
console.log(data);
}).catch((err) => {
console.log(`error ${err}`);
});
};
//server.js
app.post('/api/uploadresume', api.UploadAlumniResume);
//api.js
exports.UploadAlumniResume = (req, res) => {
console.log('req.body', req.body);
console.log('req.file', req.file);
};
i am getting file data inito $scope.Image,
and i append the data using of const fd = new FormData().
fd as append the $scope.Image.
then store the $scope.theData data to the post request.
i am getting result is:
// req.body $ req.file consoles
req.body { i: {} }
req.file undefined
I need to access the req.body data and read and fs write the req.file data .
please give any solution to me !
You can't put a FormData inside an object that you're posting. It has to be the data itself.
const fd = new FormData();
fd.append('file', $scope.Image);
$http({
method: 'POST',
url: '/api/uploadresume',
data: fd,
processData: false
})
when you are image or file uploading , you need to pass header 'Content-Type': 'multipart/form-data'
if you are using bodyparser , then body parser is not able to handle form-data , it is only handle application/x-www-form-urlencoded and application/json data
as you getting req.file undefined this because bodyparser not work with form-data
so use multer to handle form-data.

How to POST file via jQuery to nodejs connect-busboy

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');
}
});

Send two JSON via same HTTP message

I have a Nodejs and d3.js programs which handle json data, send it via cross-domain and save a file. I have two JSON array which are: nodes and links. I need to save these into a file in another domain. In front-end side I am preparing http message like this,
function sendLinks()
{
jQuery(document).ready(function($)
{
$.ajax({
type:'POST',
url: 'http://192.168.80.143:2800/',
data:JSON.stringify(links),
contentType: "application/json; charset=utf-8",
dataType: 'json',
processData: false,
error: function(data)
{
console.log("error", data);
},
success: function(data)
{
console.log("success", data);
}
});
});
}
In the server side, I have the following code(nodejs)
app.use(function(req, res) {
//write a file
fs.writeFile('links.json', JSON.stringify(req.body), function(err) {
if(err) return console.log(err);
console.log('File created > links.json');
});
res.setHeader('Content-Type', 'application/json');
res.write('Message taken: \n');
res.end(req.body);
res.send("OK");
});
I want to do that for nodes JSON array in a different file name(e.g. nodes.json). How can I do that? Can I handle with the same http message?
Thanks,
Just return data: JSON.stringify({ links: links, nodes: nodes }), and unpack appropriately at serverside.

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.

Categories