Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

NodeJS Rest API To Delete Uploaded Image

NodeJS Rest API To Delete Uploaded Image

This Rest Api tutorial help to Delete images from folder using nodejs. This is second part of tutorial Create Nodejs API to Upload file Using Multer.

I will create HTTP DELETE Rest API to delete uploaded image from server.

Now, We will extend above tutorial code and add delete image API using nodejs express framework.I am passing image name as parameter, you can pass id or other params based on your requirement.The nodejs have fs module for work with the file system on your computer.

Rest API to Delete Image

I am assuming you have configured my previous tutorial code, if not – not worries , You can also integrate this code with your existing nodejs app. I will demonstrate one by one steps to create delete image API.

Import Node.js file system module

We will import fs module into main nodejs entry file, I am adding below line into app.js file.

,fs = require('fs')

Nodejs API to Delete Image

Let’s create new rest end point to delete image, we will add below code into this file.

const DIR = 'uploads';
app.delete('/api/v1/delete/:imagename',function (req, res) {
  message : "Error! in image upload.";
    if (!req.params.imagename) {
        console.log("No file received");
        message = "Error! in image delete.";
        return res.status(500).json('error in delete');
    
      } else {
        console.log('file received');
        console.log(req.params.imagename);
        try {
            fs.unlinkSync(DIR+'/'+req.params.imagename+'.png');
            console.log('successfully deleted /tmp/hello');
            return res.status(200).send('Successfully! Image has been Deleted');
          } catch (err) {
            // handle the error
            return res.status(400).send(err);
          }
        
      }

});

Here, The imagename variable will have image name which you want to delete.The unlinkSync method of fs module help to delete image from the folder path.The DIR constant will have upload directory path.

If everything fine, You will get success message ‘Successfully! Image has been Deleted’ otherwise get ‘error in delete’ message.

The post NodeJS Rest API To Delete Uploaded Image appeared first on Rest Api Example.



This post first appeared on Rest Api Example, please read the originial post: here

Share the post

NodeJS Rest API To Delete Uploaded Image

×

Subscribe to Rest Api Example

Get updates delivered right to your inbox!

Thank you for your subscription

×