express实现文件下载

2020-04-28  本文已影响0人  我有一条小黑狗

const parser = require('ua-parser-js');

            let ua = parser(req.headers['user-agent']);

            if (['Edge', 'Chrome', 'Firefox'].indexOf(ua.browser.name) > -1) {

                res.download(filePath, filename, function (err) {

                        if (err) {

                            logger.error('有错误');

                            logger.error(err)

                        }

                        else {

                        }

                    }

                );

            }

            else {

                let mimetype = mime.lookup(filePath);

                res.setHeader('Content-type', mimetype);

                if (ua.browser.name == 'IE') {

                    res.setHeader('Content-Disposition', 'attachment; filename=' + encodeURIComponent(filename));

                } /*else if (ua.browser.name == 'Firefox') {

                res.setHeader('Content-Disposition', 'attachment; filename*="utf8\'\'' + encodeURIComponent(filename) + '"');

                } */ else {

                    /* safari等其他非主流浏览器只能自求多福了 */

                    res.setHeader('Content-Disposition', 'attachment; filename=' + new Buffer(filename).toString('binary'));

                }

                let filestream = fs.createReadStream(filePath);

                filestream.pipe(res);

            }

上一篇下一篇

猜你喜欢

热点阅读