一、新建Express项目:
我参考了这篇论文:从零搭建express + vue开发环境
二、编写文件下载代码:
使用Express的download方法。文件预先放在本地了。后期我试试放在MinIO上,是否也是一样可以实现下载。
download.js:
router.get('/introduction', function (req, res, next) {
// res.send('响应成功!')
try {
res.download('./file/introduction/课程简介.pdf')
} catch (error) {
return res.status(500).send({
result: 'error',
message: `Failed to download file: ${error.message}`
})
}
});
在app.js里加上:
app.use('/download', downloadRouter)
这样调用接口就是"/download/introduction"。
使用npm start启动项目。
三、在Vue项目里使用接口
3.1 编写统一前缀
api.js:
const base = 'http://ip:3000/download'
export default { base }
3.2 调用
一开始我使用了axios发送get请求调用,但是遇到了错误:
明明我在浏览器里输入url请求是好的:
于是我用a标签的href属性了。。。。。
使用a v-bind:href=“link”,而不是把url写死在标签里。
<template>
<div class="q-pa-md q-gutter-md">
<q-list bordered padding class="rounded-borders" style="max-width: 700px">
<q-item-label header>试题库下载</q-item-label>
<q-item clickable v-ripple>
<q-item-section avatar top>
<q-avatar icon="text_snippet" color="primary" text-color="white" />
</q-item-section>
<q-item-section>
<q-item-label lines="1"><a v-bind:href="link">无线传感器网络试题库附答案.pdf</a></q-item-label>
<q-item-label caption>3.09 MB</q-item-label>
</q-item-section>
<q-item-section side>
<q-icon name="file_download" color="grey" />
</q-item-section>
</q-item>
</q-list>
</div>
</template>
<script>
import api from 'src/api/api'
export default {
name: 'Excercise',
data () {
return {
link: api.base + '/excercise'
}
}
}
</script>
<style scoped>
</style>