as mentioned above, I tried to download the file from node (the file format is unified to zip) to the local front end through get request. I tried two ways:
- enter the spliced url directly into the browser address bar.
- after stitching the url at the front end, click on the a tag to download.
Mode 1, normal download is correct. The downloaded zip can be decompressed normally
Mode 2, the local files of chrome node are correct and can be decompressed normally. However, when downloading to the front end, chrome will give a warning as follows, and the files downloaded to the front end cannot be unzipped
Resource interpreted as Document but transferred with MIME type
when prompted to process get requests in the node background, when ContentType is set to text/html, the warning disappears, but files downloaded to the front end cannot be decompressed properly.
always thought it was a ContentType setting problem, but searched and tried for a long time and still didn"t solve it.
Click the download code
with the front-end analog a tag attached below. $.ajax({
type:"POST",
url:"/api/download_reports",
data:JSON.stringify(msgArr),
dataType:"json",
contentType:"application/json; charset=utf-8",
success:function(response){
console.log(response)
if(response.status == 200){
path = file+"?dir="+response.data.dir+"&name="+response.data.fileName;
console.log(path)
let a = document.createElement("a");
a.href = path;
a.download = response.data.fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
},
});
the following is the code for the node side to process the get request
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),
fReadStream;
fs.exists(currFile,function(exist) {
if(exist){
res.set({
"Content-type":"application/octet-stream",
"Content-Disposition":"attachment;filename="+encodeURI(fileName)
});
fReadStream = fs.createReadStream(currFile);
fReadStream.on("data",(chunk) => res.write(chunk,"binary"));
fReadStream.on("end",function () {
res.end();
});
}else{
res.set("Content-type","text/html");
res.send("file not exist!");
res.end();
}
});
});
I don"t know what the problem is. If you know, please don"t hesitate to comment on orz
.