i want to develope and application in node.js where i shud b able to upload a video in my page and store a link to that video in database(mongodb).when i click //to the link the vedio should get displayed.also i shud b able to display all the //video's uploaded in the page.I tried to code to upload phot
//new show photo code
app.get('/photos', function(req, res) {
photos.list(function(err, photo_list) {
res.render('photos/index', {locals : {
photos: photo_list
}});
});
});
app.get('/photos/new', function(req, res){
res.render('photos/new', {
locals: {
title: 'New File Upload'
}
});
});
app.post('/photos', function(req, res) {
req.setEncoding('binary');
var parser = multipart.parser();
parser.headers = req.headers;
var ws;
parser.onpartBegin = function(part) {
consol.log('inside begin');
ws = fs.createWriteStream(__dirname + '/static/upload/photos.' + part.filename)
ws.on('error', function(err) {
throw err;
});
};
parser.onData = function(data) {
ws.write(data);
};
parser.onPartEnd = function() {
ws.end();
parser.close();
console.log('file successfully uploaded');
res.redirect('/photos');
};
req.on('data', function(data) {
console.log('shud not go here');
parser.write(data);
});
});
//can any one send me the code for the same or else find were i am doing //wrong.....answer immediately required....
You should use formidable for file uploads in Node.js, it's a widely used library for such a thing.
Related
want to save csv file in mongodb with node js i used javascript to to add and fetch data but it get error
get('/import', function(req, res, next) {
var stocks1 = [];
var csvStream = csv()
.on("data", function(data){
// var errorCount = 0;
// var csvStream = csv.parse({strictColumnHandling: true, headers: true}) .on("data", function(data){
var item = new Stock({
Diamondcode: data[0],
Sortdesc: data[1],
Colour: data[2],
Size: data[3],
Meserment:data[4] ,
Price:data[5]
});
item.save(function(error){
console.log(item);
if(error){
throw error;
}
});
}).on("end", function(){
console.log(" End of file import");
});
// stream.pipe(csvStream);
res.json({success : "Data imported successfully.", status : 200});
}).get('/fetchdata', function(req, res, next) {
Stock.find({}, function(err, docs) {
if (!err){
res.json({success : "Updated Successfully", status : 200, data: docs});
} else {
throw err;
}
});
That is because you haven't given the path of your CSV. One traditional way I used in my node projects as
kept route file different and pass your csv file in form data and then access it as req.files.
Make sure you create a wrapper for your CSV conversion
This is my router module:
router.post("/", function (req, res, next) {
var url = req.body.url;
youtubedl.getInfo(url, function (err, info) {
// handle errors here
if (err) {
console.log(err);
res.status(500).send("youtube-dl error");
} else {
var fields = info.title.split('-');
var artist = sanitizeArtistOrTitle(fields[0].trim());
// TODO: handle possibility of - in artist/song name
var title = sanitizeArtistOrTitle(fields[1].trim());
const options = {
apiKey: geniusKey,
title: title,
artist: artist,
optimizeQuery: true
};
geniusSong(options)
.then(function (result) {
urlFields = result.url.split('/');
// check if the name of the song and artist are in the url
// since the api seems to return a random lyric page
// when the actual page cannot be found
var titleAndArtist = urlFields[3].split('-').join(' ').toLowerCase();
if (titleAndArtist.includes(artist.toLowerCase()) &&
titleAndArtist.includes(title.toLowerCase())) {
// get the lyrics and write to a file
req.options = options;
next();
} else {
res.status(500).send("genius API error on retrieving lyrics");
}
}).catch(function (err) {
console.log(err);
res.status(500).send("genius API unknown error");
})
}
})
}, function (req, res) {
console.log(__dirname);
geniusLyrics(req.options)
.then(lyrics => sanitizeLyrics(lyrics))
.then(sanitizedLyrics => fsPromise.writeFile("./aux_files/words.txt",
sanitizedLyrics.toString()))
.then(console.log("written to file"))
.then(res.status(200).sendFile(path.join(__dirname, "../aux_files", "words.txt"),
{headers: {'Content-Type': 'text/plain'}}))
.catch(function (err) {
console.log(err);
res.status(500).send("Could not write lyrics to file");
});
})
function sanitizeLyrics(lyrics) {
var regexp = /\[[\w ]*\]/g;
return lyrics.replace(regexp, '');
}
// remove unncessary parts of the video title e.g. "feat. ...",
// "[Official Music Video]"
function sanitizeArtistOrTitle(value) {
var regexp = /(ft\..*$|\(.*$|\[.*$|feat\..*$)/
return value.replace(regexp, '');
}
module.exports = router
And in app.js I have:
var lyrics = require('./routes/lyrics');
app.use('/api/lyrics', lyrics);
What I don't understand is that the route returns a 404 when it's called by my frontend:
POST /api/lyrics 404 4400.863 ms - 351
I can see in my filesystem that the file has been written, so I know that the middleware executed successfully, but I'm not sure where the error is coming from. If I try to fetch from the route again (after the file has been created), there is no error and everything works properly.
I am working on an express node app that posts to twitter when a user inputs an image into a form. I am saving the image locally before uploading, which works. After I encode the file to base64, I try to upload the base64-encoded file to Twitter using twit's media/upload feature. When I do this, I get an error saying "media type unrecognized."
Here is my code:
app.post('/tweet', function(req, res){
var time = new Date().getTime()
let image = req.files.image
var imgpath = './images/img' + time + '.jpg'
image.mv(imgpath, function(err) {
if (err){
return res.status(500).send(err);
}
});
var b64content = fs.readFileSync(imgpath, { encoding: 'base64' })
T.post('media/upload', {media: b64content}, function(err, data, res) {
if (err) console.log(err);
console.log(data);
T.post('statuses/update', {status: 'posted picture at: ' + time, media_ids: [data.media_id_string]}, function(err, params, res) {
if (err) console.log(err);
console.log(params);
});
});
return res.redirect('/')
})
Thank you!
Got it!. I needed to put the T.post code in the brackets of image.mv's function
use postMediaChunked function
var filePath = '/absolute/path/to/file.png'
T.postMediaChunked({ file_path: filePath }, function (err, data, response) {
console.log(data)
})
I am having a problem to redirect the page after a successful file upload using multer. With the file upload i am also saving some text into the database. Here's my code.
Question :
When the file and the contents are saved in the DB how can I redirect the page to a new URL ?
I am currently using res.redirect('product/item'); but nothing happens. I also tried using res.render, but the page did not redirect.
Multer method to upload a file to Amazon S3
var upload = multer({
storage: multerS3({
s3: s3,
bucket: 'nameofthebucket',
metadata: function (req, file, cb) {
var ext = file.originalname.split('.').pop();
cb(null, {fieldName: 'file.fieldname' + '.' + ext});
},
filename: function(req,file,cb){
var ext = file.originalname.split('.').pop();
cb(null, Date.now() + '.' + ext);
},
key: function (req, file, cb) {
var ext = file.originalname.split('.').pop();
cb(null, Date.now() + '.' + ext);
}
})
})
var upload = upload.array('fileup', 10);
The code responsible to upload the file and the content
router.post('/uploadfileandcontent',function(req,res,next){
upload(req,res,function(err) {
if(err) {
} else {
saveRecordsToDB(req, function(err,data){
if (err) {
res.redirect('/errorpage');
} else {
res. redirect('product/item');
}
});
}
});
});
Function that saves records to DB and makes the callback
function saveRecordsToDB (req, callback){
var args = {
data: {
"name" : req.body.name, //
"age" : req.body.age
},
headers: { "Content-Type": "application/json" }
};
// registering remote methods
client.registerMethod("postMethod", "http://url/uploadfileandcontent", "POST");
var req =client.methods.postMethod(args, function (data, response) {
callback(null, 'success?');
});
req.on('error', function (err) {
console.log('error');
});
}
Note: I also made use of NODE REST CLIENT to send http request.
This should work. Tell me if it doesn't.
router.post('/uploadfileandcontent', function(req,res,next){
upload(req,res,function(err) {
if(err) {
res.send('Error while uploading.');
}
saveRecordsToDB(req, function(err,data){
if (err) {
console.log(err);
req.flash('error', { msg: 'Error while saving data.' }); // Flash message -> need to configure your template to show it
}
// Saved to DB
req.flash('success', { msg: 'Saved' });
res.redirect('/product/item'); // go to this page
});
});
});
UPDATE
You will need to include const flash = require('express-flash'); to use flash message. Then you can load it to your app like this: app.use(flash());. The app is express loaded like this: const app = express();.
In your HTML you will access it in an array. Example using Jade:
//success
if messages.success
for success in messages.success
div #{success.msg} // Saved
//Error
if messages.errors
for error in messages.errors
div #{error.msg} // Error while saving data.
I would like to move a small image from one server to another (both running node). As I search, I haven't found enough. This post remains unanswered.
As I started experimenting I wrote the following to the first server :
app.post("/move_img", function(req, res) {
console.log("post handled");
fs.readFile(__dirname + "/img_to_move.jpg", function(err, data) {
if (err) throw err;
console.log(data);
needle.post(server2 + "/post_img", {
data: data,
name : "test.jpg"
}, function(result) {
console.log(result);
res.send("ok");
});
});
});
This part seems to be working as I could be writing the data in the same server (using fs.writeFile) recreate the img.
Now as I am trying to handle the post in the other server I have a problem.
Server2:
app.post('/post_img', [ multer({ dest: './uploads/images'}), function(req, res) {
console.log("body ",req.body) // form fields
console.log("files ",req.files) // form files
res.send("got it");
}]);
This way i get an empty object in the files and the following in the body: { 'headers[Content-Type]': 'application/x-www-form-urlencoded', 'headers[Content-Length]': '45009' }
I think I could use busboy as an alternative but I can't make it to work. Any advice, tutorial would be welcome.
I solved my problem by using the following code,
server1 (using needle) :
app.post("/move_img", function(req, res) {
console.log("post handled")
var data = {
image:{
file: __dirname + "/img_to_move.jpg",
content_type: "image/jpeg"}
}
needle.post(server2 + "/post_img", data, {
multipart: true
}, function(err,result) {
console.log("result", result.body);
});
})
Server 2:
app.use('/post_img',multer({
dest: '.uploads/images',
rename: function(fieldname, filename) {
return filename;
},
onFileUploadStart: function(file) {
console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function(file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
}
}));
app.post('/post_img', function(req, res) {
console.log(req.files);
res.send("File uploaded.");
});
An alternative for the server 1 is the following (using form-data module):
var form = new FormData();
form.append('name', 'imgTest.jpg');
form.append('my_file', fs.createReadStream(__dirname + "/img_to_move.jpg"));
form.submit(frontend + "/post_img", function(err, result) {
// res – response object (http.IncomingMessage) //
console.log(result);
});
I'd simply read your file from the first server with the function readFile() and then write it to the other server with the function writeFile().
Here you can see use of both functions in one of my servers.
'use strict';
const express = require('express');
const multer= require('multer');
const concat = require('concat-stream');
const request = require('request');
const router = express.Router();
function HttpRelay (opts) {}
HttpRelay.prototype._handleFile = function _handleFile (req, file, cb) {
file.stream.pipe(concat({ encoding: 'buffer' }, function (data) {
const r = request.post('/Endpoint you want to upload file', function (err, resp, body) {
if (err) return cb(err);
req.relayresponse=body;
cb(null, {});
});
const form = r.form();
form.append('uploaded_file', data, {
filename: file.originalname,
contentType: file.mimetype
});
}))
};
HttpRelay.prototype._removeFile = function _removeFile (req, file, cb) {
console.log('hello');
cb(null);
};
const relayUpload = multer({ storage: new HttpRelay() }).any();
router.post('/uploadMsgFile', function(req, res) {
relayUpload(req, res, function(err) {
res.send(req.relayresponse);
});
});
module.exports = router;
see multer does all the tricks for you.
you just have to make sure you use no middle-ware but multer to upload files in your node starting point.
Hope it does the tricks for you also.