前端Vue 请求后台下载PDF文件
时间: 2024-05-13 21:16:09 浏览: 15
在前端使用Vue发送请求下载PDF文件需要用到两个技术:axios和Blob。
首先,在Vue项目中安装axios:
```
npm install axios --save
```
然后,在Vue组件中使用axios发送请求下载PDF文件:
```javascript
import axios from 'axios'
export default {
methods: {
downloadPDF() {
axios({
url: 'your-backend-api',
method: 'GET',
responseType: 'blob' // 返回类型为blob
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', 'file.pdf') // 下载文件名
document.body.appendChild(link)
link.click()
})
}
}
}
```
在代码中,我们设置了axios的请求类型为'GET',返回类型为'blob'。当请求成功时,我们将response.data转换为Blob类型,创建URL并生成一个a标签用于下载。将a标签添加到body中,模拟用户点击下载。最后,我们需要注意设置下载文件的文件名。
在后端,你需要设置响应头的Content-Type为'application/pdf',推荐使用node.js的mime模块来获取正确的Content-Type:
```javascript
const fs = require('fs')
const path = require('path')
const mime = require('mime')
app.get('/download', (req, res) => {
const filePath = path.join(__dirname, 'file.pdf')
const fileStream = fs.createReadStream(filePath)
const contentType = mime.getType(filePath)
res.setHeader('Content-Type', contentType)
res.setHeader('Content-Disposition', 'attachment; filename=file.pdf')
fileStream.pipe(res)
})
```
在代码中,我们使用fs模块读取文件流,使用mime模块获取正确的Content-Type并设置响应头。最后,将文件流通过管道pipe到响应中,完成下载。