如何将服务器中的文件下载到访问nodeJS服务器中的页面的机器上?
我正在使用ExpressJS,我一直在尝试这个:
app.get('/download', function(req, res){
var file = fs.readFileSync(__dirname + '/upload-folder/dramaticpenguin.MOV', 'binary');
res.setHeader('Content-Length', file.length);
res.write(file, 'binary');
res.end();
});
但是我无法获得文件名和文件类型(或扩展名)。有人能帮我一下吗?
对于静态文件,如pdf, Word文档等,只需在配置中使用Express的静态函数:
// Express config
var app = express().configure(function () {
this.use('/public', express.static('public')); // <-- This right here
});
然后把你所有的文件放到public文件夹里,例如:
/public/docs/my_word_doc.docx
然后一个常规的旧链接将允许用户下载它:
<a href="public/docs/my_word_doc.docx">My Word Doc</a>
'use strict';
var express = require('express');
var fs = require('fs');
var compress = require('compression');
var bodyParser = require('body-parser');
var app = express();
app.set('port', 9999);
app.use(bodyParser.json({ limit: '1mb' }));
app.use(compress());
app.use(function (req, res, next) {
req.setTimeout(3600000)
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept,' + Object.keys(req.headers).join());
if (req.method === 'OPTIONS') {
res.write(':)');
res.end();
} else next();
});
function readApp(req,res) {
var file = req.originalUrl == "/read-android" ? "Android.apk" : "Ios.ipa",
filePath = "/home/sony/Documents/docs/";
fs.exists(filePath, function(exists){
if (exists) {
res.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Disposition" : "attachment; filename=" + file});
fs.createReadStream(filePath + file).pipe(res);
} else {
res.writeHead(400, {"Content-Type": "text/plain"});
res.end("ERROR File does NOT Exists.ipa");
}
});
}
app.get('/read-android', function(req, res) {
var u = {"originalUrl":req.originalUrl};
readApp(u,res)
});
app.get('/read-ios', function(req, res) {
var u = {"originalUrl":req.originalUrl};
readApp(u,res)
});
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
对于静态文件,如pdf, Word文档等,只需在配置中使用Express的静态函数:
// Express config
var app = express().configure(function () {
this.use('/public', express.static('public')); // <-- This right here
});
然后把你所有的文件放到public文件夹里,例如:
/public/docs/my_word_doc.docx
然后一个常规的旧链接将允许用户下载它:
<a href="public/docs/my_word_doc.docx">My Word Doc</a>
你可以使用res.sendFile()…Sample-download.xlsx应该和这个函数在同一个目录下。
const downloadFile = (req,res) => {
var options = {
root: path.join(__dirname),
};
let fileName = "Sample-download.xlsx";
res.sendFile(fileName, options, function (err) {
if (err) {
console.log(err);
return res.status(500).json({ success: false, message: "internal server error. please try again later" });
} else {
console.log("Sent:", fileName, "at", new Date().toString());
}
});
}