nodejs实现文件下载

遇到个问题,由于和后端对接一个下载功能,第一次做不大会,所以使用了隐藏的form表单进行使用,成功下载,后来越想越不对。自己琢磨下,有了这篇博客😃

<!doctype html>
<html lang="zh-Hans">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #download {
            cursor: pointer;
        }
    </style>
    <script src="./axios2.js"></script>
</head>
<body>
<a id="download">点我下载</a>
</body>
<script>
  const btn = document.querySelector('#download');
  btn.addEventListener('click', function (e) {
    axios({
      url: 'http://localhost:8086/getFile?filename=test.txt',
      responseType: 'blob',
      method: 'get',
    }).then(function (response) {
      // handle success
      console.log(response);
    })
      .catch(function (error) {
        // handle error
        console.log(error);
      })
      .finally(function () {
        // always executed
      });
  });
</script>
</html>

//download.js
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
  const {pathname, query} = url.parse(req.url);
  const urlStr = url.parse(req.url);
  if (pathname === '/getFile') {
    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;
      });
    }
    const keys = Object.keys(queryObj);
    let data;
    keys.forEach(function (key) {
      if (key === 'filename') {
        let filepath = path.resolve(__dirname, queryObj[key]);
        console.log(filepath);
        fs.readFile(filepath, (err, data) => {
          console.log('data....');
          if (err) {
            res.end(err);
            return;
          }
          res.writeHead(200, {
            'Content-Disposition': 'attachment; filename=' + queryObj[key],
            'content-type': 'application/octet-stream',
            '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);

未完待续.

posted on 2020-01-06 10:26  2481  阅读(6569)  评论(0编辑  收藏  举报

导航