以下是egg.js的后台代码
const Controller = require('egg').Controller;
const path = require('path');
const fs = require('fs');
class HomeController extends Controller {
async index() {
const filePath = path.resolve(this.app.config.static.dir, 'file_message_to.png');
this.ctx.attachment('file_message_to.png');
this.ctx.set('Content-Type', 'image/png');
this.ctx.body = fs.createReadStream(filePath);
}
}
module.exports = HomeController;
以下是前台代码
<template>
<div @click="goDownload">按钮</div>
</template>
<script>
import axois from 'axios';
export default {
methods: {
goDownload() {
axois({
url: '/home',
method: 'post',
responseType: 'blob'
}).then(res => {
this.download(res.data, res.headers);
})
},
download(data, headers) {
// 以下的代码可以注释掉,因为本身data就是blob对象。Blob构造函数也可以接受一个Blob作为参数,所以加上也没问题
// var blob = new Blob([data], {
// type: headers['content-type']
// });
var url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = url;
a.download = 'filename.png';
a.click();
}
}
}
</script>
createObjectURL用法
objectURL = URL.createObjectURL(object);
参数:object
用于创建 URL 的 File 对象、Blob 对象或者 MediaSource 对象。
函数返回值
一个DOMString包含了一个对象URL,该URL可用于指定源 object的内容。
兼容性