【发布时间】:2020-03-01 14:43:16
【问题描述】:
我用excel4node成功创建了一个excel文件并保存在服务器中,然后我使用读取流将文件发送到客户端:
res.set({
'Content-Type': 'application/vnd.openxmlformats',
'Content-Disposition': 'attachment; filename='+filename
});
// This line opens the file as a readable stream
var readStream = fs.createReadStream(path+filename, {encoding: 'utf8'});
// This will wait until we know the readable stream is actually valid before piping
readStream.on('open', function () {
// This just pipes the read stream to the response object (which goes to the client)
readStream.pipe(res);
});
// This catches any errors that happen while creating the readable stream (usually invalid names)
readStream.on('error', function(err) {
res.end(err);
});
之后我在浏览器中获取数据并使用 Blob 下载:
var blob = new Blob([data], { type: 'application/vnd.openxmlformats' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "File.xlsx";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
当我尝试打开文件时,我收到以下消息:
"Excel found unreadable content in 'File.xlsx'. Do you want to recover the contents of this workbook? If you trust the source of this workbook, click Yes"
如果我单击“是”,Excel 会说文件已损坏且无法恢复。
我想知道如何从服务器检索 excel 文件。
【问题讨论】:
-
文件有多大?一些浏览器对数据 URL 的长度有限制。您是否也尝试过手动查看文件以查看其外观?
-
文件很小,不到10KiB,文件还可以,我用excel打开了后台创建的文件
-
不,你有没有用文本编辑器或十六进制编辑器查看从前端下载的文件?
-
是的,但这是一堆难以辨认的字符