Skip to content

Instantly share code, notes, and snippets.

@joecliff
Last active July 19, 2022 17:38
Show Gist options
  • Save joecliff/11021503 to your computer and use it in GitHub Desktop.
Save joecliff/11021503 to your computer and use it in GitHub Desktop.
make a proxy to convert http download file name in express
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);
};
@asheroto
Copy link

This won't work unless res/req are global vars, right?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment