前端与后端如何上传图片!

这边是一个简单的前端与后台的上传,后端的话是使用node.js来写的一个接口。

先看代码吧!

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <form action="">
      <input type="file" />
    </form>
    <button>点击上传图片</button>
    <img src="//i2.wp.com/127.0.0.1:3000/getimg" alt="" />
    <script>
      let form = document.querySelector("form");
      let btn = document.querySelector("button");
      btn.addEventListener("click", () => {
        let formData = new FormData(form);
        formData.append("file", form.children[0].files[0]);
        let xhr = new XMLHttpRequest();
        xhr.open("post", "http://127.0.0.1:3000/upload");
        xhr.send(formData);
        xhr.onreadystatechange = () => {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              console.log(xhr.response);
            }
          }
        };
      });
    </script>
  </body>
</html>

后台代码

const express = require("express");
const multiparty = require("multiparty");
const app = express();
const fs = require("fs");
app.post("/upload", (req, res) => {
  let form = new multiparty.Form({ uploadDir: "./upload" });
  form.parse(req, (err, fields, files) => {
    console.log(fields, "fields");
    console.log(files, "files");
  });
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.send("hello");
});
app.get("/getimg", (req, res) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  fs.readFile("./upload/1.png", (err, data) => {
   console.log(data);
    res.send(data);
  });
});
app.listen(3000, () => {
  console.log("苍蝇拍的服务器启动");
});