node.js搭建图片上传服务器

github

const express = require("express");
const fs = require("fs");
const formidable = require("formidable");
const bodyParser = require("body-parser");
const path = require("path");
const rootPath = require("app-root-path");
const { v4: uuidv4 } = require("uuid");
const app = express();
const port = 8765;
app.use(bodyParser.urlencoded());

// 跨域
app.all("*", function (req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Headers", "*");
  next();
});

app.post("/upload", function (req, res) {
  const form = new formidable.IncomingForm();
  form.keepExtensions = true; // 保留文件扩展名
  form.uploadDir = path.join(rootPath.path, "\\src\\fileServe\\temp"); // 临时存储路径
  // 数据解析
  form.parse(req, function (err, fileds, files) {
    if (err) {
      throw err;
    }
    const name = files.upload.name;
    const extensions = name.split(".").pop();
    const fileName = `${uuidv4()}.${extensions}`;
    const filePath = files.upload.path;
    // 从临时存储路径中读取文件
    const data = fs.readFileSync(filePath);
    // 将读取文件保存到新的位置
    fs.writeFile(
      path.join(rootPath.path, "\\src\\fileServe\\upload\\") + fileName,
      data,
      function (err) {
        if (err) {
          return console.log(err);
        }
        console.log(req);
        // 删除临时文件
        fs.unlink(filePath, function () {});
        // 返回文件服务器中该文件的url
        res.json({
          uploaded: 1,
          fileName: fileName,
          url: `http://${req.host}:8764/upload/${fileName}`, // 文件服务器地址
        });
      }
    );
  });
});

app.listen(port, () => {
  console.log(`API Server Port: ${port}`);
});


版权声明:本文为Tyler_zch原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。