All the PDF files are saved in the filesystem on the server, how to make the files to be downloadable in client side.
for Ex :
app.use('/pdfDownload', function(req, res){
var pathToTheFile = req.body.fileName;
readFile(pathToTheFile, function(data){
//code to make the data to be downloadable;
});
});
is the request made
function readFile(pathToTheFile, cb){
var fs = require('fs');
fs.readFile(pathToTheFile, function(err, data){
//how to make the file fetched to be downloadable in the client requested
//cb(data);
});
}
You can use express.static, set it up early in your app:
app.use('/pdf', express.static(__dirname + '/pathToPDF'));
And it will automatically do the job for you when browser navigates to e.g. '/pdf/fooBar.pdf'.
Related
I have 2 nodeJS services and I would want to upload file in a dir, from one NodeJS (backend) to another NodeJS(backend). The receiver nodeJS is an express app.
Looking for some working code sample.
PS: Couldn't find any code samples in search, since everywhere it was Multer from client to server uploads that receives multipart/form-data.
Uploading file using POST request in Node.js
Receive the file first as you correctly said using Multer. Then, you may either save the file to a temporary directory before uploading it again or just send the file as-is.
You need to setup a server running with Multer on the 2nd server that wishes to receive the file.
const express = require('express');
const app = express();
const upload = multer({ dest: 'files/' });
app.post('/upload', upload.single('file'), (req, res) => {
res.sendStatus(200);
});
app.listen(3001);
Then on the server you wish to send the file from, do something like this:
const request = require('request');
const req = request.post('localhost:3001/upload', (err, res, body) => {
if (err) throw new Error(err);
if (res && res.statusCode == 200) {
console.log('Success');
} else {
console.log('Error');
};
});
const form = req.form();
form.append('file', fs.createReadStream('./location/to/file'));
I am serving up my web application using NodeJS server (ExpressJS) currently. One of the new requirements is for the users to be able to upload large videos (potentially in gigs) to the server. They will later then be able to download them again. Could I achieve this with the current stack?
I came across tutorials using Multer JS with "multipart/form-data" specified by the front-end. If I use this, would my Express be able to serve up other HTTP requests while writing a giant single video file to the server's disk?
Having done this myself (~20GB files, without multer) I can recommend the following (Probably most of which you have considered, but for completeness):
Choose an appropriate upload control (or write your own, but basically something that chunks up the data is best. I used plupload I think)
On the server make an API to handle the received chunk data, and write it out to a temp location during upload (You may want to hash and check individual pieces as well).
Once upload complete, check file (I used a hash generated by the client, and checked it against the uploaded data)
Multer should work fine. It'll stream the data as it comes in over HTTP to a file on disk. It won't lock up your server. Then in your endpoint you have access to that file location and can do whatever you need with it.
var express = require("express");
var app = express();
var async = require('async');
var fs = require('fs');
var client = redis.createClient();
var multiparty = require('multiparty');
var util = require('util');
app.post('/',function(req,res){
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
client.get(fields.otp, function(err, reply) {
var oldpath = files.file[0].path;
var newpath = path + files.file[0].originalFilename;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.end();
});
}
}
app.listen(2001,function(){
console.log("Server is running on port 2001");
});
I have a xmlhttprequest which uploads the file and I am trying to receive it in my node-express server. but for some reason I am not able to retrieve the file content in the server. Not sure where I am missing it.
app.post('/api/uploadfiles', function(req, res) {
console.log("apicalled");
console.log(req);
console.log(req.body);
console.log(req.files);
console.log(JSON.stringify(req.files));
});
In order for you to see the files, you will need to add another middleware that parses multi-part request.
Try using connect-multiparty module like so:
var multipart = require('connect-multiparty'); //for files upload
var multipartMiddleware = multipart();//for files upload
app.post('/api/uploadfiles', multipartMiddleware, function(req, res) {
console.log("apicalled");
console.log(req);
console.log(req.body);
console.log(req.files);
console.log(JSON.stringify(req.files));
});
I have a working NodeJS+FFMPEG application. I am able to upload video files and have them converted on the server. I am using this NodeJS FFMPEG library
https://github.com/fluent-ffmpeg/node-fluent-ffmpeg
I get a message on the server when the job is complete, but how do I notify the client?? In this case a simple AIR application. Right now I can only 'hear' the initial response after a successful upload.
The initial video file was uploaded via a http POST request.
My primary node application without the dependencies is as follows
var ffmpeg = require('./lib/fluent-ffmpeg');
var express = require('express'),
multer = require('multer');
var app = express();
//auto save file to uploads folder
app.use(multer({ dest: './uploads/'}))
var temp;
app.post('/', function (req, res) {
console.log(req.body); //contains the variables
console.log("req.files ="+ req.files); //contains the file references
console.log("req.files.Filedata.path ="+ req.files.Filedata.path );
temp=req.files.Filedata.path;
// make sure you set the correct path to your video file
var proc = ffmpeg('./'+temp)
// set video bitrate
.videoBitrate(1024)
// set audio codec
.audioCodec('libmp3lame')
// set output format to force
.format('avi')
// setup event handlers
.on('end', function() {
console.log('file has been converted succesfully');
})
.on('error', function(err) {
console.log('an error happened: ' + err.message);
})
// save to file
.save('./converted/converted.avi');
res.send('Thank you for uploading!');
});
app.listen(8080);
There are two approaches you can use. The first is to poll the server from the client with AJAX GET requests every x seconds. The second approach is to use WebSockets and notify the client by sending a message to them directly.
I am trying to upload files using express and formidable (eventualy forwarding to MongoDB and GridFS). I am starting by creating a form with a field of type file. On the action of that field I use the following route....
exports.addItem = function(req, res, next){
var form = new formidable.IncomingForm(),
files = [],
fields = [];
form
.on('file', function(field, file) {
console.log(field, file);
})
.on('end', function() {
console.log('-> upload done');
});
}
Everything runs fine but when I post I don't see anything in the console and it hangs.
The route looks like the following...
app.post('/item/add', routes.addItem, routes.getPlaylist, routes.index)
Any ideas?
UPDATE
Here is an example of grabbing the file, however, this still doesn't include formidable...
https://gist.github.com/2963261
The reason it is hanging is because you need to call next() to tell Express to continue.
Also use the bodyParser() middleware in express (included by default) to get the files. Something like this:
exports.addItem = function(req, res, next){
if(req.files.length > 0)
{
// process upload
console.log(req.files);
}
next();
}