nodejs 简单文件下载

本文介绍了一个使用Node.js实现的简易HTTP文件下载服务。该服务通过解析URL中的查询字符串来确定要下载的文件名,并从指定目录中读取文件内容返回给客户端。文章展示了如何处理文件路径、读取文件并设置正确的HTTP头以触发浏览器的下载行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

const http = require('http')
const url = require('url')
const fs = require('fs')
const path = require('path')

function getQueryObj(query) {
  const queryObj = {}
  if (query.length) {
    const queryArr = query.split('&')
    queryArr.forEach((e, i) => {
      let oneQuery = e.split('=')
      let key = oneQuery[0]
      let value = oneQuery[1]
      queryObj[key] = value
    })
  }
  return queryObj
}

const server = http.createServer((req, res) => {
  const { pathname, query } = url.parse(req.url);
  const urlParser = url.parse(req.url)
  if(pathname === '/download') {
    const queryObj = getQueryObj(query)
    if ('filename' in queryObj && queryObj['filename']) {
      const filename = queryObj['filename']
      // 根据资源位置获取文件 解析文件名
      let filepath = path.resolve(__dirname, './static', decodeURIComponent(filename))
      console.log(filepath)
      fs.readFile(filepath, (err, data) => {
        if(err) {
          res.end(err)
          return
        }

        res.writeHead(200, {
          'content-disposition': 'attachment; filename=' + filename,
          'content-type': 'application/octet-stream',
          'Access-Control-Expose-Headers': 'content-disposition'
          'access-control-allow-origin': '*',
          'access-control-allow-headers': 'X-Requested-With',
          'access-control-allow-methods': 'PUT,POST,GET,DELETE,OPTIONS'
        })
        fs.createReadStream(filepath).pipe(res)
      })
    }
  }
})

server.listen(8086, (err) => {
  if (!err) {
    console.log('服务已启动')
  }
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值