multer上传文件的问题

问题描述 投票:0回答:1

我想在基于

React
构建的网站上上传图像。我对后端
Node.js
代码有疑问。

代码:

const multer = require("multer");

// Check if the directory exists, if not, create it
const directory = path.join(__dirname, "../src/assets/img/images");

if (!fs.existsSync(directory)) {
    fs.mkdirSync(directory);
}

console.log("Directory: ", directory);

// Set up multer storage and file filter
// Set up multer middleware
const uploadMulter = multer({
    storage: multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, directory); // Save files to the "src/assets/img/images" directory
        },
        filename: (req, file, cb) => {
            cb(null, file.originalname); // Use the original file name
        }
    }),
    fileFilter: (req, file, cb) => {
        // Accept only image files
        if (file.mimetype.startsWith("image/")) {
            console.log("Success!!!");
            cb(null, true);
        } else {
            console.log("Error!!!!");
            cb(new Error("Invalid file type. Only image files are allowed."));
        }
    }
});

interface FileContent {
  fileName: string;
  content: string;
  type: string;
}

// Route for file upload
app.post("/upload/images", uploadMulter.array("files[]"), (req, res) => {
    // Retrieve the uploaded files from req.files array
    const files = req.files;
    // You can now process the uploaded files (e.g., save to database, manipulate, etc.)
    // For example, if you want to read the content of each file:
    const fileContents: FileContent[] = [];
    files.forEach((file) => {
        console.log("FileError: ", file.fileError);
        console.log("file.fileError.message: ", file.fileError.message);
        const data = fs.readFileSync(file.path, "binary");
        fileContents.push({fileName: file.originalname, content: Buffer.from(data, "binary").toString("base64"), type: file.mimetype}); //, fileError: error
    });

    // Send response
    res.status(200).json({files: fileContents});
});

此时,它只是打印到服务器控制台。如果用户选择文本文件而不是图像,我想向用户打印此错误:

文件类型无效。仅允许使用图像文件。

但这对我来说失败了。有什么想法如何将此错误返回给用户吗?

reactjs node.js typescript multer
1个回答
0
投票

要在用户上传类型无效的文件时向用户返回错误消息,您可以在路由中间件中处理错误并发送包含错误消息的响应。尝试这样的事情,

// Route for file upload
app.post("/upload/images", uploadMulter.array("files[]"), (req, res, next) => {
    // Check if multer encountered any error
    if (req.files.some(file => file.fileError)) {
        // If there's an error, return the error message to the user
        return res.status(400).json({ error: req.fileError.message });
    }
    ... rest of your code
});
© www.soinside.com 2019 - 2024. All rights reserved.