项目场景:
后端:Java
前端:vue+element+axios
问题描述:
后端接口返回文件流,前端调用实现前端导出功能
解决方案:
1、接口
export function websiteStatementDownloadApi(data) {
return request({
url: websiteStatementDownloadUrl,
method: 'post',
data,
responseType: "blob"
})
}
2、request文件service.interceptors.response.use(
response => {
const res = response.data
if (response.headers['content-type'] === 'application/octet-stream;charset=utf-8') {
return response
}
// ......其他
const isBlob = response.config.responseType === 'blob'
if (!isBlob) {
Message({
message: (res.msg || 'Error'),
type: 'error',
duration: 5 * 1000
})
}
}
),
3、调用接口组件<el-button @click="fetchWebsiteStatementDownload">导出</el-button>
import { websiteStatementDownloadApi} from '@/api/home'
import moment from 'moment'export default {
data(){
return{
selectedDate: {
startDate: moment(new Date().getTime() - 3600 * 1000 * 24 * 7).format('yyyy-MM-DD'),
endDate: moment().format('yyyy-MM-DD')
}
}
},
methods:{
fetchWebsiteStatementDownload() {
websiteStatementDownloadApi(this.selectedDate).then(res => {
if (res.status === 200) {
const blob = new Blob([res.data], {
type: 'application/octet-stream',
})
const reader = new FileReader()
reader.readAsDataURL(blob)
reader.onload = (e) => {
const link = document.createElement('a');
link.download = `${this.selectedDate.startDate}to${this.selectedDate.endDate}.csv`;
link.href = e.target.result;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
this.$message.success('下载成功')
}
}
}).catch(e => console.log(e, 'error'))
},
}
}
4、实现效果
遗留问题:
Headers里的返回值
打印出来的参数
后端接口已返回文件名在headers的 "content-disposition"里,但打印出来只有content-length和content-type,就只好用请求参数拼了一样格式的名字代替了。小朋友,是不是有好多问号???
原创:https://www.panoramacn.com
源码网提供WordPress源码,帝国CMS源码discuz源码,微信小程序,小说源码,杰奇源码,thinkphp源码,ecshop模板源码,微擎模板源码,dede源码,织梦源码等。专业搭建小说网站,小说程序,杰奇系列,微信小说系列,app系列小说
免责声明,若由于商用引起版权纠纷,一切责任均由使用者承担。
您必须遵守我们的协议,如果您下载了该资源行为将被视为对《免责声明》全部内容的认可-> 联系客服 投诉资源www.panoramacn.com资源全部来自互联网收集,仅供用于学习和交流,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。 敬请谅解! 侵权删帖/违法举报/投稿等事物联系邮箱:2640602276@qq.com未经允许不得转载:书荒源码源码网每日更新网站源码模板! » 记一次前端导出功能
关注我们小说电影免费看关注我们,获取更多的全网素材资源,有趣有料!120000+人已关注
评论抢沙发