Last active
July 19, 2022 17:38
-
-
Save joecliff/11021503 to your computer and use it in GitHub Desktop.
make a proxy to convert http download file name in express
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var request = require('request'); | |
function setDownloadName(req, res, fileName) { | |
var userAgent = (req.headers['user-agent'] || '').toLowerCase(); | |
if (userAgent.indexOf('chrome') > -1) { | |
res.setHeader('Content-Disposition', 'attachment; filename=' + encodeURIComponent(fileName)); | |
} else if (userAgent.indexOf('firefox') >-1) { | |
res.setHeader('Content-Disposition', 'attachment; filename*="utf8\'\'' + encodeURIComponent(fileName) + '"'); | |
} else { | |
res.setHeader('Content-Disposition', 'attachment; filename=' + new Buffer(fileName).toString('binary')); | |
} | |
} | |
/** | |
* make a proxy to convert http download file name | |
* eg. | |
* if browser request: /download-proxy?url=http://domain/not-readable-file.png&name=readable-file.png, | |
* then will get a download attachment named readable-file.png | |
*/ | |
function downloadProxy(req, res) { | |
req.setEncoding('utf8'); | |
var url = req.query.url; | |
var name = req.query.name; | |
setDownloadName(req, res, name); | |
var stream = request.get(url).pipe(res); | |
stream.on('error', function (err) { | |
res.send(500, err); | |
}); | |
} | |
module.exports = function (app) { | |
app.get('/download-proxy', downloadProxy); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This won't work unless res/req are global vars, right?