node 第六天 客户端结合原生node实现简单图片请求预览下载功能

  1. 功能核心主要是前端请求后端返回图片二进制数据, XML responseType应该设置为blob接收二进制
    然后前端通过blob api将接收到的二进制对象转为blob对象, 通过前端的blob对象可以实现图片预览和下载
  2. 前端代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>请求图片预览下载</title>
  </head>
  <body>
    <img src="" alt="" />
    <a href="">点我下载</a>
  </body>
  <script>
    let ajax = new XMLHttpRequest();
    ajax.open('POST', 'http://127.0.0.1:3003/request-img', true);
    ajax.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
    ajax.responseType = 'blob';
    const imgInfo = { name: 'kun.jpg' };
    ajax.send(JSON.stringify(imgInfo));
    ajax.onreadystatechange = function () {
      if (ajax.readyState === 4) {
        const blob = new Blob([ajax.response], { type: 'image/jpeg' });
        // document.querySelector('img').src = URL.createObjectURL(ajax.response);
        const url = URL.createObjectURL(blob);
        document.querySelector('img').src = url;
        const oA = document.querySelector('a');
        oA.href = url;
        oA.download = imgInfo.name;
      }
    };
  </script>
</html>

3.node代码

const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE');
  if (req.method === 'OPTIONS') {
    res.writeHead(200);
    res.end();
  } else if (req.url === '/request-img') {
    req.on('data', chunk => {
      let { name } = JSON.parse(chunk.toString('utf-8'));
      fs.readFile(path.normalize('./file/' + name), (err, data) => {
        if (err) {
          res.writeHead(200, { 'Content-Type': 'text/plain' });
          res.end('no this image');
          return;
        }
        res.writeHead(200, { 'Content-Type': 'image/jpeg' });
        res.end(data);
      });
    });
  } else {
    res.writeHead(200, { 'content-type': 'text/plain' });
    res.end('只接受图片请求');
  }
});
server.listen(3003);

这部分也是简单的前后端基础通信, 就不过多阐述了~
鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 kun~~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值