Reputation: 633
I want to download a textFile from the NodeJS server to the clients local machine with AngularJS as frontend. Where the client storage path is on it's local machine in downloads/testdownload.
in my backend I have:
router.get('/upload', function(req, res){
var data= fs.readFileSync('../uploads/'+ file);
fs.writeFile(??+req.file.filename, file, function(err){
if(err){
return console.log(err);
}
console.log('Saved File: ' + req.file.filename);
})
})
in my Angular:
this.download= function(){
$http.get('/creations/upload').then(function success(response){
console.log(response.data);
}, function error(response){
response.data;
})
}
I linked this function with a button. What path do I have to write in the nodejs fs.writeFile function to save the file to the local machine /downloads/testfile?
Upvotes: 0
Views: 2326
Reputation: 574
If you know the full path of the file in server, you can put that in an html anchor tag to download it right?
<a href="http://<path to file>">Download</a>
Upvotes: 0
Reputation: 7156
This will help you.. here i used busboy for posting and getting file.
This is back-end code. Just you have to call this api from front-end.
'use strict'
var express = require('express');
var router = express.Router();
var fs = require('fs-extra');
//Get file
router.get('/:file', function(req, res, next) {
//this is where your file will be downloaded
var filenamewithpath = '/home/downloads/' + req.params.file;
if (!fs.existsSync(filename)){
res.status(404).json({'message' : 'file not found'})
return;
}
res.download(filename , fileToShow)
});
//Post file
router.post('/', function(req, res, next) {
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
var fstream = fs.createWriteStream('/home/temp/' + filename);
file.pipe(fstream);
fstream.on('close', function () {
res.status(201).json({file: filename});
});
});
});
module.exports = router;
Upvotes: 1