js 通过文件流下载的xlsx文件 无法打开
时间: 2023-12-10 12:40:14 浏览: 41
可能是因为你的代码中未正确设置响应头部的Content-Type和Content-Disposition。你需要在响应头部中设置Content-Type为"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",并且设置Content-Disposition为"attachment; filename=yourfilename.xlsx",其中yourfilename.xlsx为你下载文件的文件名。
以下是一个示例代码片段,可以用于通过文件流下载xlsx文件并正确打开:
```javascript
const express = require('express');
const app = express();
const fs = require('fs');
const path = require('path');
app.get('/download', function(req, res) {
const filePath = path.join(__dirname, 'yourfilename.xlsx');
const stat = fs.statSync(filePath);
res.writeHead(200, {
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Content-Length': stat.size,
'Content-Disposition': 'attachment; filename=yourfilename.xlsx'
});
const stream = fs.createReadStream(filePath);
stream.pipe(res);
});
```
请注意替换文件名为你下载的文件名,并确保你的文件路径正确。