nodejs - - - - - 文件上传

文件上传

1. 代码如下

// 引入需要的依赖(multer需要提前安装)
const multer = require("multer");
const path = require("path");
const fs = require("fs");



const imgPath = "/keep/"; // 文件保存的相对路径

let updateBaseUrl =
  process.env.NODE_ENV === "production"
    ? "https://xxx.xxxx.com"
    : "http://127.0.0.1:8080";

let imgDirPath =
  process.env.NODE_ENV === "production"
    ? "服务器上传路径" + imgPath
    : "本地上传路径" + imgPath;


// 确保上传目录存在
fs.promises.mkdir(imgDirPath, {
    
     recursive: true }).catch(console.error);


const storage = multer.diskStorage({
    
    
  destination: (req, file, cb) => cb(null, imgDirPath),
  filename: (req, file, cb) => {
    
    
    const {
    
     name, ext } = path.parse(file.originalname);
    const uniqueSuffix = `${
      
      Date.now()}-${
      
      Math.round(Math.random() * 1e9)}`;
    cb(null, `${
      
      name}-${
      
      uniqueSuffix}${
      
      ext}`);
  },
});


// 一些限制
const multerConfig = multer({
    
    
  storage,
  limits: {
    
     fileSize: 10 * 1024 * 1024 }, // 限制文件大小为10MB
  fileFilter: (req, file, cb) => {
    
    
    const allowedMimeTypes = ["image/png", "image/jpeg", "image/jpg"];
    cb(null, allowedMimeTypes.includes(file.mimetype));
  },
});

/**
 * 保存图片资源
 * @param {*} req
 * @param {*} res
 * @returns
 */
exports.upload = (req, res) => {
    
    
  console.log("上传接口 自定义方法触发");
  return new Promise((resolve, reject) => {
    
    
    multerConfig.single("file")(req, res, (err) => {
    
    
      if (err) {
    
    
        console.log("获取资源失败 抛出错误");
        console.error("Error occurred during upload:", err.message);
        return reject(
          new Error("Error occurred during upload: " + err.message)
        );
      }
      console.log("获取资源成功 拼接url");
      console.log("File uploaded successfully:", req.file.filename);
      resolve(`${
      
      updateBaseUrl}/common/image/${
      
      req.file.filename}`);
    });
  });
};


/**
 * 获取图片资源
 * @param {*} req
 * @param {*} res
 * @returns
 */
exports.getFile = (req, res) => {
    
    
  return new Promise((resolve, reject) => {
    
    
    const filePath = path.join(imgDirPath, req.params.filename);
    fs.promises
      .access(filePath, fs.constants.F_OK)
      .then(() => resolve(filePath))
      .catch(() => {
    
    
        console.error("File not found:", req.params.filename);
        reject(new Error("File not found"));
      });
  });
};

猜你喜欢

转载自blog.csdn.net/Dark_programmer/article/details/139961216