原生H5单文件上传 前端+node后端

79 阅读1分钟

前端代码

<!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>
    <input class="choose" type="file" /> <button class="upload">上传</button>

    <!-- 引入axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
      let chooseInp = document.querySelector(".choose");
      let uploadBut = document.querySelector(".upload");

      // 初始化一个FormData表单
      let fm = new FormData();

      // 选择文件时获取文件信息并储存在表单中
      chooseInp.onchange = (e) => {
        let file = e.target.files[0];
        fm.append("file", file);
      };

      uploadBut.onclick = () => {
        axios
          .post("http://127.0.0.1:3000/upload", fm, {
            // 固定请求头字段表示传递的是文件流
            headers: {
              "Content-Type": "multipart/form-data",
            },
          })
          .then((r) => {
            if (r.data.code == 1) {
              alert("上传成功");
            } else {
              alert("上传失败");
            }
          });
      };
    </script>
  </body>
</html>

后端代码

// 引入express 框架
const express = require("express");
// 引入文件处理中间件
const multer = require("multer");
// 引入路径模块
const path = require("path");
// 设置cors头解决跨域
const cors = require("cors");

const app = express();

app.use(cors()); //使用cors中间件

// 创建multer的配置内容
const storage = multer.diskStorage({
  // 设置前端传来的文件存放地址(file是定义的一个文件夹进行存放前端传来的数据的)
  destination: function (req, file, cb) {
    cb(null, "./file");
  },
  // 设置保存的文件名称,这里是使用的file的fieldname加上时间戳再加上前端传过来的文件后缀名及进行重新命名
  filename: function (req, file, cb) {
    // 文件后缀  file.originalname 为原文件名
    let extname = path.extname(file.originalname);
    let filename = Date.now() + extname;
    cb(null, filename);
  },
});

const upload = multer({ storage });

app.post("/upload", upload.single("file"), (req, res) => {
  res.json({ code: 1 });
});

// 启动服务器
app.listen(3000, () => {
  console.log("服务器已启动");
});

package.json

{
  "name": "serve",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.18.2",
    "multer": "^1.4.5-lts.1",
    "path": "^0.12.7"
  }
}

文件目录

image.png

使用方法:
1.先创建package.json 文件,npm i 或 yarn 安装依赖包
2.node index.js 启动服务器

最基础的文件上传了,有问题欢迎提问.