Java删除单个本地文件

效果图:

Java删除单个本地文件_第1张图片

html:

 
  • 删除事件:

    function deletefile(fileurl){
    	$.ajax({
    		type:"post",
    		url:"deletefile.do",
    		data:{
    			"fileurl":fileurl,
    			"responseType":"ajax"
    		    },
    		dataType:"json",
    		success:function(data){
        		    if(data.status==1){
    			toastr.success('删除成功!');
    			$("#fileslist").load("${ctx}/admin/core/user/uploadface.do?isjson=true&userId="+$("#studentId").val());
    		    }
    		}
    	})
    }

    后台:

    	@RequestMapping("deletefile.do")
    	public String deletefile(String fileurl, HttpServletRequest request, HttpServletResponse response,
    			org.springframework.ui.Model modelMap) {
    		Response resp = new Response(request, response, modelMap);
    		String fullPath = pathResolver.getPath(fileurl);
    		File file = new File(fullPath);
    		if (!file.isDirectory()) {
    			file.delete();
    		}
    		return resp.post(1);
    	}

     

    获取路径的接口及实现方法:

    public interface PathResolver {
    	public String getPath(String uri);
    
    	public String getPath(String uri, String prefix);
    }
    
    package com.course.common.web;
    
    import java.io.File;
    
    import javax.servlet.ServletContext;
    
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.web.context.ServletContextAware;
    
    /**
     * ServletContext路径获取实现
     * 
     */
    public class ServletContextPathResolver implements PathResolver,
    		ServletContextAware {
    	public String getPath(String uri) {
    		if (uri == null) {
    			uri = "";
    		}
    		StringBuilder sb = new StringBuilder();
    		sb.append(servletContext.getRealPath(""));
    		if (!uri.startsWith("/")) {
    			sb.append(File.separator);
    		}
    		sb.append(uri.replace('/', File.separatorChar));
    		return sb.toString();
    	}
    
    	public String getPath(String uri, String prefix) {
    		if (uri == null) {
    			uri = "";
    		}
    		StringBuilder sb = new StringBuilder();
    		if (StringUtils.startsWith(prefix, "file:")) {
    			sb.append(prefix.substring(5));
    		} else {
    			sb.append(servletContext.getRealPath(""));
    			if (StringUtils.isNotBlank(prefix)) {
    				sb.append(prefix.replace('/', File.separatorChar));
    			}
    		}
    		if (!uri.startsWith("/")) {
    			sb.append(File.separator);
    		}
    		sb.append(uri.replace('/', File.separatorChar));
    		return sb.toString();
    	}
    
    	private ServletContext servletContext;
    
    	public void setServletContext(ServletContext servletContext) {
    		this.servletContext = servletContext;
    	}
    }

     

    你可能感兴趣的:(Java)