js 另存为 a 下载 html 下载



(推荐)前端方法:
<a href="http://localhost:3000/upload/index_logo.gif" download="xxx">下载11</a> //下载后是xxx.gif
*注意所下载的文件必须是同域名不然无法实现另存为效果,仅仅不兼容IE。谷歌、火狐,Edge兼容
如果下载需要token验证,参考https://sdeno.com/?p=8002
后端方法:
例如php需要设置
header('Content-type: image/jpeg'); header("Content-Disposition: attachment; filename='download.jpg'");
这里以koa2为案例:
路由设置
router.get('xxxpath', (ctx) => { ctx.set('Content-disposition','attachment;filename=name.txt'); // 设置你的文件名 const data = new Buffer('Im a example of text') // 创建一个buffer ctx.body = data // 返回在响应体里 });
前端设置
<a onclick="window.open('xxxpath')">下载</a> //下载后会得到一个txt,内容是Im a example of text
—————————————
为了方便将其他文件也转化为Buffer,推荐使用
npm i urllib -S
const urllib = require('urllib'); router.get('down',async ctx=>{ let file = await urllib.request('https://sdeno.com/wp-content/themes/flat_ui/img/icons/png/jquery.png'); ctx.set('Content-disposition','attachment;filename='+'name.jpg'); ctx.body=file.data; //返回的是 Buffer类型 });
https://www.zhangxinxu.com/wordpress/2016/04/know-about-html-download-attribute/