How to delete file from folder using javascript?

前端 未结 6 1012
故里飘歌
故里飘歌 2020-12-16 00:51

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

function deleteImage(file_name)
    {
        var r = confirm(\"Are you          


        
相关标签:
6条回答
  • 2020-12-16 01:06

    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.

    0 讨论(0)
  • 2020-12-16 01:08

    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
              }
            });
        }
    }
    
    0 讨论(0)
  • 2020-12-16 01:08

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

    0 讨论(0)
  • 2020-12-16 01:09

    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);
    
    0 讨论(0)
  • 2020-12-16 01:10

    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 !!');
        }
       }
      });
    });
    });
    
    0 讨论(0)
  • 2020-12-16 01:14

    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.

    0 讨论(0)
提交回复
热议问题