使用AJAX和Spring Boot从磁盘删除文件

时间:2017-08-31 05:10:02

标签: java jquery ajax spring spring-boot

我正在尝试使用Ajax和Spring启动技术从磁盘(本地或服务器)中删除文件。

到目前为止,我已经尝试过这个:

的Ajax / jquery的:

            $(".ct-color-specs").on("click",".color-spec-file-delete",function() {
                    var deletedFileName = $(this).parents(".ct-attached-color-spec-files").find("a").text();
                    $.ajax({

                        url : "/Application/removeFile/"+deletedFileName",
                        type: 'DELETE',  
                        success: function (res) {  
                            console.log(data);
                        } 
                    });
                });

控制器:

 @RequestMapping(value = "/removeFile",produces="text/html", method = RequestMethod.DELETE)
    public String removeFileHandler(@PathVariable("deletedFileName") String filepath, Model model) {
        String removeFileCheck = "false";
        try{

            System.out.println("Delete filepath from AJX");
            File file = new File(filepath);

            if(file.delete()){
                System.out.println(file.getName() + " is deleted!");
                removeFileCheck="true";
            }else{
                System.out.println("Delete operation is failed.");
            }

        }catch(Exception e){

            e.printStackTrace();

        }
        model.addAttribute("checkList", removeFileCheck);
        return "p/view";
    }

错误:

  

"未找到"消息:"没有可用消息"路径:   " /Application/removeFile/File.pdf"状态:404

2 个答案:

答案 0 :(得分:0)

您以错误的格式编写了@RequestMapping(value =" / removeFile" ...)

弹簧中的路径变量如下所示

@RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET)
     public String getLogin(@PathVariable("userId") String userId,
         @PathVariable("roleId") String roleId){
         System.out.println("User Id : " + userId);
         System.out.println("Role Id : " + roleId);
         return "hello";
     }

答案 1 :(得分:0)

我将在这里写答案,因为我用下面的代码解决了。

<强>控制器:

@RequestMapping(value = "/removeFile/{deletedFileName}", method = RequestMethod.GET)
public String removeFileHandler(@PathVariable("deletedFileName") String filepath, Model model) {
       .....
    }

<强> AJAX / jquery的:

            $(".ct-color-specs").on("click",".color-spec-file-delete",function() {
                    var deletedFileName = $(this).parents(".ct-attached-color-spec-files").find("a").text().split('/').pop().split('\\').pop();;
                    alert("deletedFileName--->" + deletedFileName);
                     $.ajax({
                        url : "/Application/removeFile/"+deletedFileName,
                        type: 'GET',  
                        success: function (res) {  
                            console.log(data);
                        } 
                    });
                });