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);

未完待續.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM