利用 ajax 上传图片 删除图片 (Spring Boot)

效果如下:

 

 

1.启动类中

SpringBoot重写addResourceHandlers映射文件路径

@Override
	 public void addResourceHandlers(ResourceHandlerRegistry registry) {
	     registry.addResourceHandler("/imctemp-rainy/**").addResourceLocations("file:D:/E/");
	 }

设置静态资源路径

 

2.   表单 前端 页面

<input type="file" name="file" id="file">
<p id="url"><img src="" width=200></p>
<input type="button" id="button" value="上传" >
<input type="button" id="t_button" value="取消上传" >
$(function () {
	    $("#button").click(function () {
	        var form = new FormData();
	        form.append("file", document.getElementById("file").files[0]);
	         $.ajax({
	             url: "/news/upload",        //后台url
	             data: form,
	             cache: false,
	             async: false,
	             type: "POST",                   //类型,POST或者GET
	             dataType: 'json',              //数据返回类型,可以是xml、json等
	             processData: false,
	             contentType: false,
	             success: function (data) {      //成功,回调函数
	                 if (data) {
	                	 var pic="/imctemp-rainy/"+data.fileName;
	                	 alert(pic);
	                 	 $("#url img").attr("src",pic);
	                 	 // alert(JSON.stringify(data));
	
	                 } else {
	                 	alert("失败");
	                 }
	                 
	             },
	             error: function (er) {          //失败,回调函数
	            	 alert(JSON.stringify(data));
	             }
	         });
	    });
	    
	    $("#t_button").click(function () {
             //这里分割字符串 /imctemp-rainy/157352875235607c10257539a5f4dcdaab233ca2832a5.jpg
             //需要用/分割字符先后获取最后一段字符串去上传到后台
         	 //alert($("#url img").attr("src"));
         	 var img = $("#url img").attr("src");
         	 var str = img.split("/");
         	 var str_img=str[str.length-1];
		     //alert(str_img);
	         $.post("/news/deleteImages",{filePath:str_img},function(data){
	        	 alert(data);
                  //这里我们取消上传成功之后去给换成一个暂无图片的一个图
	        	 $("#url img").attr("src","/imctemp-rainy/no.jpg");
	         });
	    });
	})

控制器

public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {        
			File targetFile = new File(filePath); 
			if (!targetFile.exists()) {
			   targetFile.mkdirs();    
			}        
			FileOutputStream out = new FileOutputStream(filePath +"/"+ fileName);
			out.write(file);      
			out.flush();   
			out.close(); 
	}
    //处理文件上传
  	@ResponseBody //返回json数据  
  	@RequestMapping(value = "upload", method = RequestMethod.POST) 
  	public JSONObject uploadImg(@RequestParam("file") MultipartFile file,HttpServletRequest request) {        
  	    String contentType = file.getContentType(); 
  	    //System.out.print(contentType);
  		String fileName = System.currentTimeMillis()+file.getOriginalFilename();
  		String filePath = "D:/E";
	    JSONObject jo = new JSONObject();//实例化json数据

  		if (file.isEmpty()) {   
  			jo.put("success", 0);
  			jo.put("fileName", "");
  		}        
  		try {  
  		   uploadFile(file.getBytes(), filePath, fileName);  
  		   jo.put("success", 1);
  		   jo.put("fileName", fileName);
  		  // jo.put("xfileName", filePath+"/"+fileName);
  		} catch (Exception e) {  
  		// TODO: handle exception        
  	
  		}   
		 

  		//返回json
  	    return jo;    

  	}    
  	
  	
  	@ResponseBody //返回json数据  
  	@RequestMapping("deleteImages")
  	public String deleteImages(HttpServletRequest request) {
  		String resultInfo = null;
  	    String filePath = request.getParameter("filePath");
        //这里是可以在控制器分割字符的一个方法
  	    //int lastIndexOf = filePath.lastIndexOf("/");
  	    //String sb = filePath.substring(lastIndexOf+1,filePath.length());
        //由于我们只获取了图片的名称并没有获取到所有的地址,,所以我们需要去给他进行添加存放图片的地址
  		File file = new File("D:/E/"+filePath);
  		if (file.exists()) {
			if (file.delete()) {
				resultInfo = "1-删除成功";
			}else {
				resultInfo = "0-删除失败";
			}
		}else {
			resultInfo = "文件不存在!";
		}
  		return resultInfo;
  	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章