【问题标题】:delete image with nodejs使用nodejs删除图像
【发布时间】:2022-02-15 21:17:21
【问题描述】:

当我在 NodeJS 中更新产品时,我想从 images 文件夹中删除旧图像,产品正在更新,但旧图像没有从文件夹中删除。

index.js

app.use(bodyParser.json({extended:true}))
app.use(bodyParser.urlencoded({extended:true}))
app.use(cors())
app.use('/', route)
app.use('/images', express.static('images'))

功能

export const updateProduct = async (req, res)=>
{
    try{
        let image 
        const oldProduct = await Product.findOne({_id:req.params.id})
        const {name,price,quantity,category} = req.body
        
        if(req.file)
        {
         image = req.file.filename
         const oldImageUrl= `/images/${oldProduct.image}`

          // this is url of the old image http://localhost:2001/images/1629969633380_r.png

         await  fs.unlinkSync(oldImageUrl)

        }else{
            image = oldProduct.image
        }
        const productToUpdate = new Product({name,category,quantity,price,image})
        await Product.updateOne({_id:req.params.id},productToUpdate)
        
         res.status(200).json('product Updated')
     }catch(error)
     {
         res.status(404).json({message:error.message})
     }
}

【问题讨论】:

  • 我之前也遇到过这个问题,请尝试杀死您的应用并重新启动它。
  • fs.unlinkSync(oldImageUrl) 不返回承诺

标签: node.js express


【解决方案1】:

基于这段代码:

app.use('/images', express.static('images'))

您应该尝试删除相对于应用程序文件夹的图像。

const oldImageUrl= `images/${oldProduct.image}`

或者更好的是,使用path 模块。

const { join } = require('path');
...
const oldImageUrl = join(__dirname, 'images', oldProduct.image);

【讨论】:

    【解决方案2】:
    router.post('/update/:id', upload.single("file"), async (req, res) => {
            let data = {
                name: req.body.name,
                price: req.body.price,
                quantity: req.body.quantity,
                discount: req.body.discount,
                discription: req.body.discription,
                file: req.file.filename
            }
            const oldProduct = await products.findOne({ _id: req.params.id });
            const result = await products.findByIdAndUpdate(req.params.id, data,);
            fs.unlink('./public/image/' + oldProduct.file, function (err) {
                if (err && err.code == 'ENOENT') {
                    // file doens't exist
                    console.info("File doesn't exist, won't remove it.");
                } else if (err) {
                    // other errors, e.g. maybe we don't have enough permission
                    console.error("Error occurred while trying to remove file");
                } else {
                    console.info(`removed`);
                }
            });
            res.redirect('/listProducts');
        })
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多