在multer图像上传(nodejs)中出现错误

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

我没有在 image.buffer 中获得价值 在调试时,我在 imageObject 中得到了以下值

Image object: {
  fieldname: 'image',
  originalname: 'technoduce.png',
  encoding: '7bit',
  mimetype: 'image/png',
  destination: 'D:\\My Project\\Pjt EmployeeTrackingSystem\\ets_nodejs\\uploads',
  filename: '1715079481440_technoduce.png',
  path: 'D:\\My Project\\Pjt EmployeeTrackingSystem\\ets_nodejs\\uploads\\1715079481440_technoduce.png',
  size: 1880080
}

我的要求: 我需要将图像保存在项目文件夹中并在响应中返回图像 url。创建用户时,我需要在请求正文中传递图像 url。 所以我使用了 multer 包。它非常适合将图像保存到本地文件夹。但是,在 writeFileSync 步骤中,我没有收到 image.buffer 值。所以我不能去那之后。请协助我解决这个问题。预先感谢。

服务.js

const fs = require('fs');
const path = require('path');

const uploadImage = async (image) => {
    try
    {
        console.log("Image object:", image);

        const filename = Date.now() + '_' + image.originalname;
        const imagePath = path.join(__dirname, './uploads', filename); //path where the image will be saved
        console.log("ImagePath", imagePath);
        console.log("Buffer", image.buffer);
        //const data = Buffer.from(image.buffer)
        fs.writeFileSync(imagePath, image.buffer); // Write the image data to the file system
        return `/uploads/${filename}`; 
    }
    catch (error)
    {
        console.error("Error uploading image:", error);
        throw new Error('Failed to upload image');
    }
};

module.exports = {
    uploadImage
};

app.js

  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, 'uploads')); // Save uploaded images to the 'uploads' directory
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + '_' + file.originalname); // Rename the uploaded file with a unique name
  }
});

const upload = multer({ storage: storage });

// Serve uploaded images statically
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.post('/uploadImage', upload.single('image'), async (req, res) => {
  try {
      if (!req.file) {
      return res.status(400).json({ message: 'No image uploaded' });
    }
    // Upload the image and get the URL
    const imageUrl = await uploadImage(req.file);
    res.status(200).json({ imageUrl });
  } catch (error) {
    console.error("Error uploading image:", error);
    res.status(500).json({ message: 'Failed to upload image' });
  }
});

我尝试使用不同的包,但它不起作用。

node.js multer
1个回答
0
投票

您可以使用

memoryStorage
那么文件信息对象将包含
buffer
属性。它没有任何选项。

const multer = require('multer');
const storage = multer.memoryStorage();
const upload = multer({ 
    storage: storage,
    limits:{
        fieldSize: 10485760 // 10mb
    } 
});
© www.soinside.com 2019 - 2024. All rights reserved.