react如何下载文件
使用 fetch 或 axios 下载文件
通过 fetch 或 axios 发送请求获取文件数据,将响应转换为 Blob 对象,并创建下载链接。
示例代码(fetch):
fetch('文件URL')
.then(response => response.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = '文件名.扩展名'; // 设置下载文件名
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
});
示例代码(axios):
axios.get('文件URL', { responseType: 'blob' })
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const a = document.createElement('a');
a.href = url;
a.download = '文件名.扩展名';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
});
使用 <a> 标签直接下载
适用于无需鉴权的静态文件,直接通过 HTML 标签触发下载。
示例代码:
<a href="文件URL" download="文件名.扩展名">下载文件</a>
处理后端返回的文件流
若后端返回文件流(如 Node.js 的 res.download),确保前端正确解析 Blob 并触发下载。
后端示例(Node.js Express):
app.get('/download', (req, res) => {
res.download('服务器文件路径', '客户端文件名.扩展名');
});
前端处理:

fetch('/download')
.then(response => response.blob())
.then(blob => {
// 同上述 Blob 处理逻辑
});
注意事项
- 跨域问题:确保文件 URL 允许跨域请求(CORS 配置)。
- 鉴权:需鉴权的文件需在请求头中添加
Authorization等字段。 - 大文件处理:考虑分块下载或进度提示(如
axios的onDownloadProgress)。
通过以上方法,可根据实际需求选择适合的下载方式。






