nodejs res.download() file - javascript

i'm pretty new to nodejs and stuff, and i;ve been researching on how to upload and download a file from a nodejs server
the upload part works just fine, the problem is the download part
the code i wrote has no errors but however, the file itself is not downloading, i have no idea where i went wrong
here's my uploadss.js file
var express = require('express');
var multer = require('multer');
var path = require('path');
var fs = require('fs');
var app = express();
var router = express.Router();
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, __dirname + '/uploads');
},
filename: function (req, file, callback) {
callback(null, Date.now() + path.extname(file.originalname));
}
});
var upload = multer({ storage : storage }).array('userPhoto',5);
app.set('views', __dirname + '/views');
app.get('/index', function(req, res){
res.render('indexss.ejs');
});
app.use('/', router);
app.post('/api/photo', function(req, res){
upload(req, res, function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
router.get('/download', function(req, res) {
var dir = path.resolve(".") + '/uploads/';
fs.readdir(dir, function(err, list) {
if (err)
return res.json(err);
else
res.json(list);
});
});
router.get('/download/:file(*)', function(req, res, next){
var file = req.params.file;
var path = require('path');
var path = path.resolve(".") + '/uploads/' + file;
res.download(path, file, function(err){
if (err){
console.log(err);
} else {
console.log('downloading successful');
}
});
});
app.listen(8080);
and here's the indexss.ejs file that contains the html and javascript
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
<script>
$(document).ready(function() {
$('#uploadForm').submit(function() {
$("#status").empty().text("File is uploading...");
$(this).ajaxSubmit({
error: function(xhr) {
console.log(xhr);
status('Error: ' + xhr.status);
},
success: function(response) {
$("#status").empty().text(response);
console.log(response)
}
});
return false;
});
$.ajax({
url: "/download",
method: "get",
success: function(data){
downloadArray = data;
for (i = 0; i < downloadArray.length; i++){
console.log(downloadArray[i]);
console.log(typeof downloadArray[i]);
$('#downloadList').append("<a href='#' onclick='downloadFile(this)'>" + downloadArray[i] + "</a><br>");
}
}
});
});
function downloadFile(selectedFile){
fileToDownload = $(selectedFile).text();
console.log(fileToDownload);
$.ajax({
url: "/download/" + fileToDownload,
method: "get",
success: function(){
console.log('successful downloading');
}
});
}
</script>
</head>
<body>
<form id="uploadForm"
enctype="multipart/form-data"
action="/api/photo"
method="post">
<input type="file" name="userPhoto" multiple />
<input type="submit" value="Upload" name="submit">
<input type='text' id='random' name='random'><br>
<span id = "status"></span>
</form>
<div id='downloadList'></div>
</body>

You're overriding path with filename parameter. Try this:
res.download(path);
And read res.download(path [, filename] [, fn]) at: https://expressjs.com/en/api.html

try the following code
server
var app = express();
var fs = require('fs');
app.get('/image', function (req, res) {
var path_image = req.headers.path;
var src = fs.createReadStream(path_image);
src.on('open', function () {
src.pipe(res);
log.info('down completed: ' + path_image);
});
src.on('error', function (err) {
log.error('' + err);
});
});
path_image is your file path, i use the client-side information sent
java-client use library https://github.com/koush/ion
Ion.with(MainActivity.this)
.load("http://IP:PORT/image")
.setHeader("path", path_image_on_server)
.progress(new ProgressCallback() {
#Override
public void onProgress(long downloaded, long total) {
Log.e("bc", "" + downloaded + " / " + total);
}
})
.write(new File(path_image_save_file))
.setCallback(new FutureCallback<File>() {
#Override
public void onCompleted(Exception e, File file) {
if (e != null) {
Log.e("bc", e.toString());
}
if (file != null) {
Log.e("bc", file.getAbsolutePath());
}
}
});

Related

How can I put input value to the JSON in node.js file

I was making the TODO list web application.
This is the 'todo.html' code below :
<html>
<head>
<title>My TODO List</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="main.css">
<script>
$(document).ready(function() {
$("#submit").click(function() {
var bla = $('#item').val();
$("#todo").append("<li class='todoVal'>" + bla + "</li>");
});
// $(document).click(function(e) {
// if (e.target.className == 'todoVal') {
// var t = e.target.innerText
// $(e.target).remove();
// $("#completed").append("<li class='completedVal'>" + t + "</li>");
// }
// });
$(document).click(function(e) {
if (e.target.className == 'completedVal') {
$(e.target).remove();
}
});
jQuery.fn.single_double_click = function(single_click_callback, double_click_callback, timeout) {
return this.each(function() {
var clicks = 0,
self = this;
jQuery(this).click(function(event) {
clicks++;
if (clicks == 1) {
setTimeout(function() {
if (clicks == 1) {
single_click_callback.call(self, event);
} else {
double_click_callback.call(self, event);
}
clicks = 0;
}, timeout || 500);
}
});
});
}
$(document).single_double_click(function(e) {
if (e.target.className == 'todoVal') {
var t = e.target.innerText
$(e.target).remove();
$("#completed").append("<li class='completedVal'>" + t + "</li>");
}
}, function(e) {
if (e.target.className == 'todoVal') {
$(e.target).remove();
}
});
$("#clear").click(function() {
$("li").remove();
});
});
</script>
</head>
<body>
<div id="addItem" class="box">
Task:
<input id="item" type="text" name="add_item" />
<button id="submit" type="button">Add</button>
<button id="clear" type="button">Clear All</button>
</div>
<div id="todo" class="box">
<h4>TODO:</h4>
<ul></ul>
</div>
<div id="completed" class="box">
<h4>Completed:</h4>
<ul></ul>
</div>
</body>
</html>
And this is the 'app.js' file below :
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require("body-parser");
// middleware
app.use(cors());
app.use(bodyParser.json());
var tasks = [];
// This will serve the HTML page todo.html
app.get('/', function(req, res) {
res.sendFile('todo.html', {
root: __dirname
});
});
// GET all tasks
app.get('/tasks', function(req, res) {
res.set('Content-Type', 'application/json')
res.status(200).send(tasks);
});
// POST to add a task
app.post('/task', function(req, res) {
res.set('Content-Type', 'application/json')
/* HELP ME HERE */
// returns 201 on success
res.status(201);
});
// DELETE a task
app.delete('/task', function(req, res) {
/* HELP ME HERE */
// returns 204 on success
res.status(204);
});
// DELETE all tasks
app.delete('/tasks', function(req, res) {
/* HELP ME HERE */
// returns 204 on success
res.status(204);
});
//
// Listen for HTTP requests on port 3000
app.listen(3000, function() {
console.log("listening on port 3000");
});
I want to pass the text box value to the JSON filter by 'TODO' and 'COMPLETED'.
If I add a new TODO list, it goes to the JSON and if the value goes to COMPLETED, it also goes to the JSON
This is the sample JSON result I want:
{"TODO" : [ "Go to market", "Eat dinner with Daniel"], "COMPLETED" : [ "Wash dishes", "Go to gym and Workout" ]}
This is just an example so you guys can just change the format.
Feel free to give me feedback from everything it's always welcome. btw I just started studying how to code
Thank you for spending time on this even if you didn't help me and have a great day!
What you have to do is simply make an Ajax Call to Nodejs APIs. For example,to '/task' and pass the input field value as params in json format then simply fetch them on in Nodejs as req.params.yourjsonKeys.
var inputData = $("#items").val();
$.ajax({
url: "/tasks",
type: "POST",
data: {params: inputData},
dataType: "html",
success: function(data){
if(data.code === 200){ // the response key 'code' from Nodejs
alert('Success');
}
}
});
Next, once you have the params, all you have to do is write it into your file using file system like so:
Create a javascript object with the table array in it
var obj = {
table: []
};
Add some data to it like
obj.table.push({id: req.params.id , square: req.params.square});
Convert it from an object to string with stringify
var json = JSON.stringify(obj);
//use fs to write the file to disk
var fs = require('fs');
fs.writeFile('myjsonfile.json', json, 'utf8', callback);
if you want to append it read the json file and convert it back to an object
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
obj = JSON.parse(data); //now it an object
obj.table.push({id: 2, square:3}); //add some data
json = JSON.stringify(obj); //convert it back to json
fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
}});
Complete Code:
// POST to add a task
app.post('/task', function(req, res) {
res.set('Content-Type', 'application/json')
var obj = {
table: []
};
obj.table.push({id: req.params.id , square: req.params.square});
var json = JSON.stringify(obj);
var fs = require('fs');
fs.writeFile('myjsonfile.json', json, 'utf8', callback)
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
obj = JSON.parse(data); //now it an object
obj.table.push({id: 2, square:3}); //add some data
json = JSON.stringify(obj); //convert it back to json
fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
// returns 201 on success
res.json({
code: 201,
message: 'Success'
});
}});
});

Node request module with fs.createWriteStream() creates an empty file

I'm trying to upload an external url to my server. Here's what I got so far
var fs = require('fs');
var request = require('request');
var path = require('path');
const imagesFolder = 'downloadedAssets/imgs';
function download(url, dest, filename, cb) {
var file = fs.createWriteStream(dest + "/" + filename + path.extname(url));
request( {url: url}, function(err, response) {
if(err) {
console.log(err.message);
return;
}
response.pipe(file);
file.on('error', function(err) {
console.log(err.message);
file.end();
});
file.on('finish', function() {
file.close(cb);
});
});
}
and then executing the function...
var url = 'http://pngimg.com/uploads/spongebob/spongebob_PNG44.png';
download(url, imagesFolder, 'sponge', function onComplete(err) {
if (err) {
console.log(err.message);
} else {
console.log('image uploaded to server');
}
});
This doesn't throw any errors, and it creates a file name sponge.png, but the file is empty. Any idea why?
You might have mixed up the examples on the official website
Try using pipe() like below.
function download(url, dest, filename, cb) {
var file = fs.createWriteStream(dest + "/" + filename + path.extname(url));
request( {url: url}).pipe(file);
}

Uploading an image in express just hangs

html:
<form method='post' action='upload_bg' enctype="multipart/form-data">
<input type='file' name='fileUploaded'>
<input type='submit'>
My index.js
app.route('/upload_bg')
.post(function (req, res) {
var fstream;
req.busboy.on('file', function (fieldname, file, filename) {
console.log(filename);
fstream = fs.createWriteStream(__dirname + '/imgs/' + "latest_upload.jpg");
file.pipe(fstream);
fstream.on('close', function () {
res.redirect('back');
});
});
});
My variables:
var express = require('express');
var busboy = require('connect-busboy');
var path = require('path');
var fs = require('fs-extra');
So the user clicks the button, selects an image, and selects submit. This hit's my route upload_bg. I've had it working before, and I changed a few things around but I'm unable to understand why it isn't working. I look in the network tab and the request is just pending indefinitely.
Here is my simple solution using express-fileupload module:
First intall express fileupload module using following command:
npm install express-fileupload
HTML page code:
<html>
<body>
<form ref='uploadForm'
id='uploadForm'
action='http://localhost:3000/upload_bg'
method='post'
encType="multipart/form-data">
<input type="file" name="sampleFile" />
<input type='submit' value='Upload!' />
</form>
</body>
</html>
node server code:
server.js:
var express=require('express');
var app = express();
var fileUpload = require('express-fileupload');
// default options
app.use(fileUpload());
app.post('/upload_bg', function(req, res) {
if (!req.files)
return res.status(400).send('No files were uploaded.');
// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
let sampleFile = req.files.sampleFile;
// Use the mv() method to place the file somewhere on your server
// Make sure 'imgs' folder is already created inside current directory otherwise it will throw error where this server.js file is placed
sampleFile.mv(__dirname + '/imgs/latest_upload.jpg', function(err) {
if (err)
return res.status(500).send(err);
res.send('File uploaded!');
});
});
app.listen(3000,function(){
console.log("App listening on port 3000")
});
Hope this will help. For complete code refer https://github.com/richardgirges/express-fileupload
I would personally re-style your code a little bit. And I would use ajax. Here is some example code:
index html:
<button class="btn btn-lg upload-btn" type="button">Upload image</button>
<input id="upload-input" type="file" name="uploads[]" multiple="multiple">
client js:
This can/should be inside of index.html
$('.upload-btn').on('click', function (){
$('#upload-input').click();
$('.progress-bar').text('0%');
$('.progress-bar').width('0%');
});
$('#upload-input').on('change', function(){
var files = $(this).get(0).files;
if (files.length > 0){
// create a FormData object which will be sent as the data payload in the
// AJAX request
var formData = new FormData();
// loop through all the selected files and add them to the formData object
for (var i = 0; i < files.length; i++) {
var file = files[i];
// add the files to formData object for the data payload
formData.append('uploads[]', file, file.name);
}
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data){
console.log('upload successful!\n' + data);
},
});
}
});
server js:
var express = require('express');
var app = express();
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');
var l;
//... other code here
app.get('/upload', function(req, res){
res.sendFile(path.join(__dirname, 'index.html'));
});
app.post('/upload', function(req, res){
var form = new formidable.IncomingForm();
form.multiples = true;
form.uploadDir = path.join(__dirname, '/uploads');
form.on('file', function(field, file) {
fs.readdir('uploads/', function(err, items) {
console.log(items.length);
l = items.length
console.log(l);
fs.rename(file.path, "uploads/"+l+".jpg", function(err) {
if ( err ) console.log('ERROR: ' + err);
});
});
});
form.on('error', function(err) {
console.log('An error has occured: \n' + err);
});
form.on('end', function() {
res.end('success');
});
form.parse(req);
});
Hope this helps!

Data not correctly loaded with Node.js using express.js, fs and handlebars

I am kinda new to Node.js and experienced a strange behavior in my application.
At the beginning I am reading all uploaded files to my server using fs.readdir. Then the data is getting stored like this:
// Store all files and their data
var uploads = [];
var docData = [];
//read all files when server starts
fs.readdir(dir, function(err, items) {
if(err) {
console.log("Could not read files from directory " + dir);
}
else {
uploads = items;
uploads.forEach(function(item) {
var path = dir + item;
textract.fromFileWithPath(path, function( err, text ) {
if(err) {
console.log("Could not parse file " + path);
}
else {
var val = {
name : item,
data: text
};
docData.push(val);
}
});
});
}
});
So I store on the one hand the raw files and on the other hand the extracted text as json. But it does not load the files properly. It looks like the items are handed out to the frontend before these arrays are set, but I am not sure about this problem. The data is given to the frontend in this way:
app.get('/:search', function(req, res){
var result = [];
var invalidItems = 0;
for (var i = 0; i < docData.length; i++) {
if(!(stringStartsWith(docData[i].name,"."))) {
var index = i + 1 - invalidItems;
result.push({id: index, doc: docData[i].name, count: 3});
}
else{
invalidItems++;
}
}
res.send(result);
});
And the handlebars template using jade looks like this:
// Template for search results
script#result-template(type='text/x-handlebars-template')
table#data.table.table-striped.table-bordered
thead
tr
th ID
th Document
th Count
th Delete
tfoot
tr
th ID
th Document
th Count
th Delete
tbody
| {{#each this}}
tr
td {{id}}
td
a(href="/uploads/{{doc}}") {{doc}}
td {{count}}
td
span.glyphicon.glyphicon-trash
| {{/each}}
Is there any "clear" way to ensure that all the uploaded data has been parsed before sending the result to the frontend or do you think there is another stupid mistake?
Edit: The call in the js looks like that:
var needle = $('input[name=srch-term]').val();
$.ajax({
url: "http://localhost:1234/"+needle,
type: 'GET',
success: function (resp)
var source = $("#result-template").html();
var template = Handlebars.compile(source);
$("#result").html(template(resp));
},
error: function(e) {
alert('Error: '+e.text);
}
});
The complete app.js looks like this:
var express = require('express');
var path = require('path');
var http = require('http');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var elasticsearch = require('elasticsearch');
var multer = require("multer");
var fs = require('fs');
var textract = require('textract');
var app = express();
var upload = multer({ dest : './public/uploads'});
var dir = './public/uploads/';
// Store all files and their data
var uploads = [];
var docData = [];
//read all files when server starts
fs.readdir(dir, function(err, items) {
if(err) {
console.log("Could not read files from directory " + dir);
}
else {
uploads = items;
uploads.forEach(function(item) {
var path = dir + item;
textract.fromFileWithPath(path, function( err, text ) {
if(err) {
console.log("Could not parse file " + path);
}
else {
var val = {
name : item,
data: text
};
docData.push(val);
}
});
});
}
});
require('dotenv').load();
var client = new elasticsearch.Client({
host: process.env.ES_HOST,
log: 'trace'
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use(multer({ dest: './public/uploads/',
rename: function (fieldname, filename) {
//add the current date to the filename to allow multiple uploads
return filename + Date.now();
},
onFileUploadStart: function (file) {
console.log(file.originalname + ' is starting ...');
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' uploaded to ' + file.path);
//add the uploaded file to the stored files
uploads.push(file);
textract.fromFileWithPath(file.path, function( error, text ) {
if(error) {
console.log("Could not parse file " + file.path);
}
else {
//add the uploaded file's text to the docData
var len = dir.length - 2;
var val = {
name : file.path.substring(len),
data: text
};
docData.push(val);
}
});
}
}));
app.post('/upload',function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.redirect('/');
});
});
app.get('/:search', function(req, res){
var result = [];
var invalidItems = 0;
console.log("Data = " + docData.length);
for (var i = 0; i < docData.length; i++) {
if(!(stringStartsWith(docData[i].name,"."))) {
var index = i + 1 - invalidItems;
result.push({id: index, doc: docData[i].name, count: 3});
}
else{
invalidItems++;
}
}
console.log("data; " + docData.length);
res.send(result);
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(process.env.SRV_PORT);
module.exports = app;
function stringStartsWith (string, prefix) {
var res;
try {
res = string.slice(0, prefix.length) == prefix;
}
catch(err) {
res = false;
}
return res;
}

how to serve a file (exe or rar ) to a client for download from node.js server?

I have a a node.js server that serves an index.html with a text input for a password.
After a serverside password check the download should start for the client.
The client shouldn't be able to see the location path where the file lies on the server.
here is my server.js:
var
http = require('http'),
qs = require('querystring'),
fs = require('fs') ;
console.log('server started');
var host = process.env.VCAP_APP_HOST || "127.0.0.1";
var port = process.env.VCAP_APP_PORT || 1337;
http.createServer(function (req, res) {
if(req.method=='GET') {
console.log ( ' login request from ' + req.connection.remoteAddress );
fs.readFile(__dirname +'/index.html', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
}
else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
}
});
} // method GET end
else{ // method POST start
console.log('POST request from ' + req.connection.remoteAddress);
var body = '';
req.on('data', function (data) {
body += data;
if (body.length > 500) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
req.connection.destroy(); console.log('too much data')}
});
req.on('end', function () {
var postdata = qs.parse(body);
var password = postdata.passwordpost ;
if (password == '7777777') {
console.log('the password is right, download starting');
// ??????????????????????????????????? here I need help from stackoverflow
}
else{
console.log ('password wrong');
fs.readFile(__dirname +'/wrongpassword.html', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
}
else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
}
});
}
}); // req on end function end
}
}).listen(port, host);
the part where I need help is marked with ????????
here is my index.html:
<html>
<body>
<br> <br>
please enter your password to start your download
<br> <br>
<form method="post" action="http://localhost:1337">
<input type="text" name="passwordpost" size="50"><br><br>
<input type="submit" value="download" />
</form>
</body>
</html>
Do you know how to do this?
Sure, you can use this in your code :
res.setHeader('Content-disposition', 'attachment; filename='+filename);
//filename is the name which client will see. Don't put full path here.
res.setHeader('Content-type', 'application/x-msdownload'); //for exe file
res.setHeader('Content-type', 'application/x-rar-compressed'); //for rar file
var file = fs.createReadStream(filepath);
//replace filepath with path of file to send
file.pipe(res);
//send file
You needs to declare and require the path: path = require("path")
then can do:
var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri);
path.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
response.writeHead(200);
response.write(file, "binary");
response.end();
}
check these complete example.
If you are willing to use express web framework, then it can be done in a much easier way.
app.get('/download', function(req, res){
var file = __dirname + 'learn_express.mp4';
res.download(file); // Sets disposition, content-type etc. and sends it
});
Express download API
I found some additional information about fs.createReadStream() ( especially error handling ) here and combined it with the answer of user568109. Here is my working downloadserver:
var
http = require('http'),
qs = require('querystring'),
fs = require('fs') ;
console.log('server started');
var host = process.env.VCAP_APP_HOST || "127.0.0.1";
var port = process.env.VCAP_APP_PORT || 1337;
http.createServer(function (req, res) {
if(req.method=='GET') {
console.log ( ' login request from ' + req.connection.remoteAddress );
fs.readFile(__dirname +'/index.html', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
}
else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
}
});
} // method GET end
else{ // method POST start
console.log('POST request from ' + req.connection.remoteAddress);
var body = '';
req.on('data', function (data) {
body += data;
if (body.length > 500) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
req.connection.destroy(); console.log('too much data')}
});
req.on('end', function () {
var postdata = qs.parse(body);
var password = postdata.passwordpost ;
if (password == '7777777') {
console.log('the password is right, download starting');
res.setHeader('Content-disposition', 'attachment; filename='+'test1.exe');
//filename is the name which client will see. Don't put full path here.
res.setHeader('Content-type', 'application/x-msdownload'); //for exe file
res.setHeader('Content-type', 'application/x-rar-compressed'); //for rar file
var readStream = fs.createReadStream('/test1.exe');
//replace filepath with path of file to send
readStream.on('open', function () {
// This just pipes the read stream to the response object (which goes to the client)
readStream.pipe(res);
});
// This catches any errors that happen while creating the readable stream (usually invalid names)
readStream.on('error', function(err) {
console.log (err) ;
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('an error occured', 'utf-8');
});
//send file
}
else{
console.log ('password wrong');
fs.readFile(__dirname +'/wrongpassword.html', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
}
else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
}
});
}
}); // req on end function end
}
}).listen(port, host);

Categories

Resources