我在服务器上有一个 pdf 文件,我想发送给客户端。我在服务器上使用 expressjs,这是编写和提供文件的代码:
function writeFile(fileStream, fileName) {
return new Promise(function (resolve, reject) {
var file = fs.createWriteStream(fileName);
fileStream.pipe(file);
filestream.on('finish', () => {
resolve();
});;
});
}
...
writeFile(fileStream, params.file).then(function() {
ftps.end();
console.log(params.file);
res.setHeader('Content-Type', 'application/pdf');
res.status(200).download(`./${params.file}`, params.file, (err) => {
if (err) {
res.status(500).send({
message: "Could not download the file. " + err,
});
}
var stats = fs.statSync(params.file);
console.log(stats.size);
fs.unlink(`./${params.file}`, function (err) {
if (err) {
throw err
} else {
console.log("Successfully deleted the file.")
}
});
});
});
然后客户端检索文件:
let toParse = await fetch(self.apiLink, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(self.params)
});
l(toParse.status);
if (toParse.status == 200) {
let parsed;
if (fileExpected) parsed = await toParse.blob();
else parsed = await toParse.json();
hideLoader();
l(parsed);
return parsed;
}
var url = window.URL.createObjectURL(toParse);
$('#pdf_frame').attr("src",url);
window.URL.revokeObjectURL(url);
一切都按预期工作,除了有时客户端上的文件有点小并且没有显示。我不知道为什么会这样,也无法在互联网上找到任何答案
发现错误:
function writeFile(fileStream, fileName) {
return new Promise(function (resolve, reject) {
var file = fs.createWriteStream(fileName);
fileStream.pipe(file);
filestream.on('finish', () => { //this should be concat to filestream.pipe(file)
resolve();
});;
});
}
所以解决方案:
function writeFile(fileStream, fileName) {
return new Promise(function (resolve, reject) {
var file = fs.createWriteStream(fileName);
fileStream.pipe(file).on('finish', () => {
resolve();
});;
});
}
现在 blob 大小在服务器和客户端之间是一致的