使用Vue、Quasar、Express开发课程网站(二):利用Express实现文件下载

一、新建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>

最后长这样

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值