前端下载文件踩坑
· 阅读需 2 分钟
服务端提供借口,返回文件流,浏览器能触发下载,但是使用file-saver下载报错或无法打开
创建服务端
创建一个接口提供文件下载,这里使用
nestjs,修改app.module.ts,并在根目录下存放一个名为download.xlsx的文件
import { Controller, Get, Header, Res, StreamableFile } from '@nestjs/common';
import { AppService } from './app.service';
import { createReadStream } from 'fs';
import { join } from 'path';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get('get-file')
@Header(
'Content-Type',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
)
@Header('Content-Disposition', 'attachment; filename=download.xlsx')
getFile(@Res({ passthrough: true }) res: Response): StreamableFile {
const file = createReadStream(join(process.cwd(), 'download.xlsx'));
return new StreamableFile(file);
}
}
创建客户端
以
vue作为前端,修改App.vue
<script lang="ts" setup>
import axios from 'axios'
import { saveAs } from 'file-saver'
// 提供服务的端口,实际端口以服务提供端口为准
const handleGetFile = async () => {
// 使用fetch
// const response = await fetch('http://127.0.0.1:3000/get-file')
// const data = await response.blob()// 注意需要设置响应类型!!!
// 使用axios
const { data } = await axios.get('http://127.0.0.1:3000/get-file', {
method: 'GET',
responseType: 'blob', // 注意需要设置响应类型!!!
})
saveAs(data, 'download.xlsx')
}
</script>
<template>
<button type="button" @click="handleGetFile">保存文件</button>
</template>
总结
下载文件时前端也需要设置响应类型