2024年03月30日 建站教程
nodejs
语法如何实现http
文件下载,下面web建站小编给大家简单介绍一下!
具体代码如下:
const http = require('http'); const fs = require('fs'); const server = http.createServer((req, res) => { console.log('Request received'); const fileUrl = req.url.slice(1); const filePath = `./${fileUrl}`; fs.stat(filePath, (err, stats) => { if (err) { res.statusCode = 404; res.end('File not found'); return; } fs.readFile(filePath, (err, data) => { if (err) { res.statusCode = 500; res.end('Error reading file'); return; } res.setHeader('Content-Disposition', `attachment; filename=${fileUrl}`); res.setHeader('Content-Type', 'application/octet-stream'); res.setHeader('Content-Length', stats.size); res.end(data); }); }); }); server.listen(3000, () => { console.log('Server started on port 3000'); });
本文链接:http://so.lmcjl.com/news/697/