How to delete file from folder using javascript?

Is there any way to delete files from folder using javascript..? Here is my function

function deleteImage(file_name) { var r = confirm("Are you sure you want to delete this Image?") if(r == true) { var file_path = <?php echo dirname(__FILE__) . '/uploads/'?>+file_name; file_path.remove(); } }
4

6 Answers

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 } }); }
}

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 !!'); } } });
});
});
4

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 can't do this. Actually JavaScript is sandboxed and it's not allowing to do such operations.

For deleting a file you need a server side scripting to achieve this. It depends on the fact that what server side language you are using to deal with.

2

Javascript is a client side scripting language. If you want to delete files from server, use php instead.

You cannot do it by using javascript. But if the file resides in the server then you can use php to do that..you can use unlink in php.

unlink($path_to_file);
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like