簡體   English   中英

錯誤:ENOENT:沒有這樣的文件或目錄 Nodejs

[英]Error: ENOENT: no such file or directory Nodejs

我正在嘗試上傳文件並將其存儲在上傳文件夾中,但我收到此錯誤: no such file or directory我在控制台中收到成功消息,但無論如何我都會收到此錯誤。

POST /auth/register 500 21.023 ms - 260
Error: ENOENT: no such file or directory, open E:\IMPORTANT\INFO-DEV\DEV\ANGULAR NODEJS\API AUTH\uploads\1671534381494.jpeg

這是我的上傳配置代碼。

const path = require("path");
const multer = require("multer");
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/");
  },
  filename: function (req, file, cb) {
    const extension = path.extname(file.originalname);
    cb(null, Date.now() + extension);
  },
});
const upload = multer({
  storage: storage,
  fileFilter: function (req, file, callback) {
    if (
      file.mimetype == "image/png" ||
      file.mimetype == "image/jpg" ||
      file.mimetype == "image/jpeg"
    ) {
      callback(null, true);
      console.log("Image téléchargé avec succès"); // success message
    } else {
      callback(null, false);
      console.log("Seulement du fichier de type png, jpg ou jpeg"); // error message
    }
  },
  limits: {
    fileSize: 1024 * 1024 * 2,
  },
});

module.exports = upload;

問題是您的uploads文件夾不存在或您設置的路徑不正確。

我不知道您到底在哪里創建了uploads文件夾(以及您是否創建了它)。

所以在目標參數中你應該傳遞:

path.join(__dirname, '/uploads') - 如果該文件夾與當前 js 文件位於同一位置。

path.join(process.cwd(), '/uploads') - 如果上傳文件夾位於項目的根目錄中(您運行npm start等)

因此,簡而言之,您需要確保文件夾存在,然后確保路徑正確。

PS 使用../../語法也應該有效,您可以嘗試../uploads../../uploads ,例如,如果該文件夾位於文件夾結構的更高級別。

改變這一行

cb(null, './uploads/');

這一行cb(null, "uploads/");

或者試試cb(__dirname, "uploads/");

你可以試試你的路徑名

img: {
  data: fs.readFileSync(
    path.join(__dirname + "../../uploads" + req.file.filename)
  ),
  contentType: "image/png",
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM