as mentioned, after the file is converted into a file stream on the node side and transferred to res through pipe , the front end configures xhr, but the response received prints the size to 0 according to the referenced data;
node get interface code is as follows:
app.get("/api/download",function(req, res, next){
var currDir = path.join(__dirname,req.query.dir),
fileName = req.query.name,
currFile = path.join(currDir,fileName),
stats = fs.statSync(currFile);
fs.exists(currFile,function(exist) {
if(exist){
res.set({
"Content-type":"application/octet-stream",
"Content-Disposition":"attachment;filename="+encodeURI(fileName),
"Content-Length": stats.size
});
let fReadStream = fs.createReadStream(currFile);
fReadStream.pipe(res);
}else{
res.set("Content-type","text/html");
res.send("file not exist!");
res.end();
}
});
});
the key code returned by the front-end receiver is as follows:
var xhr = new XMLHttpRequest();
xhr.open("get", "/api/download?dir="+response.data.dir+"&name="+response.data.fileName, true);
xhr.responseType = "blob";
xhr.onload = function() {
if (this.status == 200) {
var blob = this.response;
console.log(blob);
}};
xhr.send();
at this point, the blob printed by the front-end console is
but if you comment out the pipe on the node side, enter the following code, and the front end will get the blob with size.
//fReadStream.pipe(res);
res.send("testtesttesttest")
-Update Line-
A deeper manifestation of the problem is to directly input the stitched url in get mode into the browser and download it directly. In this case, the size of the file stream obtained by Node is not 0, but the size of the node file stream obtained through the xhr request written above is 0. There is also no difference between the two file paths obtained after careful inspection, so there is something wrong with the request method?
reference link is https://www.cnblogs.com/cdemo.