Get progression file upload - node.js

I try to get the progression of my file uploading in node Js ... I use the form-data library integrated on request library ...
Is there any way to get my progression ?
var torrentStream = require('torrent-stream');
var express = require('express');
var http = require('http');
var request
var app = express();
var request = require('request');
var zipFolder = require('zip-folder');
var magnet = require('magnet-uri')
var FormData = require('form-data');
var fs = require('fs');
var formData = {
files : fs.createReadStream(__dirname + '/archive.zip')
};
request.post({url:'http://request.url', formData: formData},
function(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});

Related

How to upload (pdf) file from FileReader to node js Express app

I have a (React) js app that reads a PDF file using FileReader then uses fetch to send it to a node js server running Express. When the request is received on the server side, however, the request body is undefined. What is missing from my code for this to work?
Client side:
function readFile() {
let file = fileInputRef.current.files[0];
const reader = new FileReader();
return new Promise((resolve) => {
reader.onload = function (e) {
resolve(e.target.result);
};
reader.readAsDataURL(file);//readAsDataURL, readAsArrayBuffer, or readAsBinaryString?
});
}
function handleSubmit(event) {
event.preventDefault();
readFile().then((value) => {
fetch('/gen/file', {
method: 'POST',
body: value
})
});
Server side:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser')
const app = express();
const jsonParser = bodyParser.json()
const port = 3000;
app.post("/gen/file", function (req, res, next) {
console.log(req.body);//undefined - Why????
});
app.listen(port, function (err) {
if (err) console.log(err);
});
Client Side:
function getBase64(file,callback){
const reader = new FileReader();
reader.addEventListener('load',()=> callback(reader.result));
reader.readAsDataURL(file);
}
function handleSubmit(event) {
event.preventDefault();
let body = {};
getBase64(file,fileUrl=>{
body.file = fileUrl;
fetch('/gen/file', {
method: 'POST',
body
})
})
Server Side:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser')
const app = express();
const jsonParser = bodyParser.json()
const port = 3000;
const fs = require('fs');
app.post("/gen/file", function (req, res, next) {
console.log(req.body);//undefined - Why????
let file = req.body.file;
let base64 = file.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
var buffer = new Buffer.from(base64[2],'base64');
fs.writeFile(__dirname+"/out.jpeg", buffer, 'base64', function (err) {
console.log(err);
});
});

unable to download videos from fb in node js

I am creating a web application using node js that can download videos from facebook, i am getting the url and quality using express using the code below but how can i download it
const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
var http = require('http');
var fs = require('fs');
app.get('/', (req,res)=>{
res.sendFile(path.join(__dirname,'templates','index.html'));
});
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(express.bodyParser());
app.post('/send_data', function(req, res) {
res.send('You sent the name "' + req.body.fbUrl + ' in '+req.body.quality+' Quality".');
if(req.body.quality == "HD")
{
download_video("HD");
}
else if(req.body.quality == "SD")
{
download_video("SD");
}
else if(req.body.quality == "MP3")
{
download_video("MP3");
}
else
{
app.get('/', (req,res)=>{
res.sendFile(path.join(__dirname,'templates','index.html'));
});
}
function download_video(quality)
{
console.log('video is downloading in "'+req.body.quality+'" Quality');
}
I don't know how are you getting the FB video URL explicitly. However, I can help you with how to download video from URL,
let http = require('http');
let fs = require('fs');
let download = (url, dest, cb) => {
let file = fs.createWriteStream(dest);
http.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(cb);
});
});
}
This will create a file stream and download the file chunk by chunk to the destination path (dest).

nodejs - Express request shape zip from geoserver return text

I am requesting a geoserver from express (node.js) for getting shape zip in wfs service, but I just got text.
var express = require('express');
var router = express.Router();
var fs = require('fs');
var request = require("request");
var DOWNLOAD_DIR = './downloads/';
router.get('/', function(req, res, next) {
var file_url='https://geo.gob.bo/geoserver/aasana/wfs?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&typeName=aerodromos&outputFormat=shape-zip';
request(file_url, function(err, resp, body) {
console.log('res',res);
console.log('body',body);
if(!err){
var file = fs.createWriteStream(DOWNLOAD_DIR + 'aerodromos');
var buff = new Buffer(body);
file.write(buff,function(err){
console.log(err);
});
file.end();
console.log(' downloaded to ' + DOWNLOAD_DIR);
}else{
console.log("No results error.",err);
}
});
res.render('index', { title: 'descargado' });
});
module.exports = router;
I am trying to put into a file zip but I cant open it.
you need to set encoding to null which will be treated as buffer rather than string in your case
request({url: file_url, encoding: null}, function(err, resp, body) {

How to parse stream from multipart data in koa2

so I'm uploading stream data inside multipart form-data
var Koa = require('koa');
var Router = require('koa-router');
const HttpStatus = require('http-status');
const fs = require('fs');
const koaBody = require('koa-body');
const request = require('request');
var FormData = require('form-data');
var formData = {
my_field: 'my_value',
my_file: fs.createReadStream('robot.jpg'),
};
request.post({url:'http://localhost:3456/fileStorage', formData: formData}, function(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
In the server side I tried koa-multer, get errors when trying to access the file. Just use the plain koa-body, I can see the file is uploaded, but cannot save it back to a file, any hints pls ?
{ my_file:
File {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
size: 15562,
path: '/var/folders/l6/lmwkwk196_qfxxngv5ys0lp00000gn/T/upload_fc48a19e6ee5abf8a9a361d784725b78',
name: 'robot.jpg',
type: 'image/jpeg',
...
}
The source is this
var Koa = require('koa');
var Router = require('koa-router');
const HttpStatus = require('http-status');
const fs = require('fs');
const koaBody = require('koa-body');
//const multiparty = require('multiparty');
//const multer = require('koa-multer');
var app = new Koa();
var router = new Router();
//const upload=multer({desk: './uploads/' });
router
.post(`/upload`, koaBody({multipart:true}),
(ctx) => {
console.log('----- hello ----');
console.log(ctx.request.body.files);
console.error('---------------');
const writeStream = fs.createWriteStream('./111.jpg');
ctx.request.body.files.my_file.pipe(writeStream);
});
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3456);
ok, I just did this
const readStream = fs.createReadStream(ctx.request.body.files.my_file.path);
so I can receive the file stream in the multipart from the http post.

Make voice call using node js

I am using Both Java web server and node js(for chat)
Now I want to make voice call using Twilio`
I wrote code like this
var fs = require('fs');
var sslOptions = {};
var path = require('path');
var express = require('express');
var app = express();
var server = require('https').createServer(sslOptions, app);
const EventEmitter = require('events');
const myEE = new EventEmitter();
server.on("request", function (req, res) {
res.end("this is the response");
});
server.listen('8090', function(){
console.log("Secure Express server listening on port 8090");
});
var accountSid = 'AC***************************';
var authToken = "******************************";
var client = require('twilio')(accountSid, authToken);
var morgan = require('morgan');
var bodyParser = require('body-parser');
var twilio = require('twilio');
var VoiceResponse = twilio.twiml.VoiceResponse;
module.exports = server;
app.use(express.static(path.join(process.cwd(), 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
app.use(morgan('combined'));
app.get('/', function(request, response) {
response.render('index');
});
app.post('/call', function(request, response) {
var salesNumber = request.body.salesNumber;
var url = 'http://' + request.headers.host + '/outbound/' + encodeURIComponent(salesNumber);
var options = {
to: '+91*******',
from: '+17******',
url: url,
};
client.calls.create(options)
.then((message) => {
response.send({
message: 'Thank you! We will be calling you shortly.',
});
})
.catch((error) => {
console.log('errot');
// console.log(error);
response.status(500).send('error');
});
});
app.post('/outbound/:salesNumber', function(request, response) {
var salesNumber = request.params.salesNumber;
var twimlResponse = new VoiceResponse();
twimlResponse.say('Thanks for contacting our sales department. Our ' +
'next available representative will take your call. ',
{ voice: 'alice' });
twimlResponse.dial(salesNumber);
response.send(twimlResponse.toString());
});
I am trying to make an ajax call from one of my javascript files to an express route
$.ajax({ url: '/call',
method: 'POST',
dataType: 'application/json',
processData: false,
data: {
phoneNumber: '+91*******',
salesNumber:'+17******** '
}
}).done(function(data) {
// The JSON sent back from the server will contain a success message
alert(data.message);
}).fail(function(error) {
//alert('errot');
alert(JSON.stringify(error));
});
when I execute this ajax call
it's looking for Java server and return 404 error
How can I solve this issue
Anyone, please help me to solve this issue

Resources