How to delete file from folder using javascript?

You can not delete files with javascript for security reasons.However, you can do so with the combination of server-side language such as PHP, ASP.NET, etc using Ajax. Below is sample ajax call that you can add in your code.

$(function(){
$('a.delete').click(function(){
  $.ajax({
   url:'delete.php',
   data:'id/name here',
   method:'GET',
   success:function(response){
    if (response === 'deleted')
    {
       alert('Deleted !!');
    }
   }
  });
});
});

Using NodeJS you can use filestream to unlink the file also.

It'd look something like this:

var fs = require('fs');
fs.unlink('path_to_your_file+extension', function (err) {
    //Do whatever else you need to do here
});

I'm fairly certain (although I havent tried it) that you can import the fs node_module in plain javascript but you'd have to double check.

If you cant import the module you can always download NPM on your machine, and

npm i fs

in some directory (command line) to get the javascript classes from that module to use on your markup page.


You cannot delete anything without any server-side script..

You can actually use ajax and call a server-side file to do that for e.g.

Make a file delete.php

<?php 
   unlink($_GET['file']);
?>

and in the javascript

function deleteImage(file_name)
{
    var r = confirm("Are you sure you want to delete this Image?")
    if(r == true)
    {
        $.ajax({
          url: 'delete.php',
          data: {'file' : "<?php echo dirname(__FILE__) . '/uploads/'?>" + file_name },
          success: function (response) {
             // do something
          },
          error: function () {
             // do something
          }
        });
    }
}

Tags:

Javascript