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~~~

你可能感兴趣的:(前端,node.js)