您可以使用 smbget( https://linux.die.net/man/1/smbget附带的 linux 实用程序),然后只需使用 node child_process spawn 来调用该函数。
只需在此处将 [workgroup]、[username]、[password]、[serveraddress] 和 [path] 替换为您自己的信息。
function getFile(file) {
return new Promise(function(resolve, reject) {
var tempFilePath = `/tmp/${file}`; // the linux machine
var remoteFile = require('child_process').spawn('smbget', ['--outputfile', tempFilePath, '--workgroup=[workgroup]', '-u', '[username]', '-p', '[password]', `smb://[serveraddress]/c$/[path]/[path]/${file}`]);
remoteFile.stdout.on('data', function(chunk) {
// //handle chunk of data
});
remoteFile.on('exit', function() {
//file loaded completely, continue doing stuff
// TODO: make sure the file exists on local drive before resolving.. an error should be returned if the file does not exist on WINDOWS machine
resolve(tempFilePath);
});
remoteFile.on('error', function(err) {
reject(err);
})
})
}
上面的代码片段返回一个承诺。因此,在节点中,您可以将响应发送到这样的路由:
var express = require('express'),
router = express.Router(),
retrieveFile = require('../[filename-where-above-function-is]');
router.route('/download/:file').get(function(req, res) {
retrieveFile.getFile(req.params.file).then(
file => {
res.status(200);
res.download(file, function(err) {
if (err) {
// handle error, but keep in mind the response may be partially sent
// so check res.headersSent
} else {
// remove the temp file from this server
fs.unlinkSync(file); // this delete the file!
}
});
})
.catch(err => {
console.log(err);
res.status(500).json(err);
})
}
响应将是要下载的文件的实际二进制文件。由于此文件是从远程服务器检索的,我们还需要确保使用 fs.unlinkSync() 删除本地文件。
使用 res.download 发送带有响应的正确标头,以便大多数现代 Web 浏览器知道提示用户下载文件。