文件上传 获取文件路径的两种方式:
/**
* 获取文件上传目录
* @return
*/
private File getUploadFileLocation(HttpServletRequest request){
File upload = null;
try {
//获取项目的编译类目录 class 位置
// File path = new File(ResourceUtils.getURL("classpath:").getPath());
//获取项目文件位置 项目位置
File path = new File(request.getSession().getServletContext().getRealPath("/"));
if(!path.exists()) path = new File("");
System.out.println("**************** path:"+path.getAbsolutePath() + "****************");
//如果上传目录为/static/images/upload/,则可以如下获取:
upload = new File(path.getAbsolutePath(),WEB_FILE_LOCATION );
if(!upload.exists()) upload.mkdirs();
System.out.println("****************** upload url:"+upload.getAbsolutePath() + "****************");
} catch (Exception e) {
e.printStackTrace();
}
return upload;
}
import org.springframework.util.ResourceUtils;
//获取项目的编译类目录 class 位置
File path = new File(ResourceUtils.getURL("classpath:").getPath());
//获取项目文件位置 项目位置
File path = new File(request.getSession().getServletContext().getRealPath("/"));
private final String WEB_FILE_LOCATION = "/fileupload";
/** * 获取文件上传目录 * @return */ private File getUploadFileLocation(HttpServletRequest request){ File upload = null; try { //获取跟目录 // File path = new File(ResourceUtils.getURL("classpath:").getPath()); File path = new File(request.getSession().getServletContext().getRealPath("/")); if(!path.exists()) path = new File(""); System.out.println("**************** path:"+path.getAbsolutePath() + "****************"); //如果上传目录为/static/images/upload/,则可以如下获取: upload = new File(path.getAbsolutePath(),WEB_FILE_LOCATION ); if(!upload.exists()) upload.mkdirs(); System.out.println("****************** upload url:"+upload.getAbsolutePath() + "****************"); } catch (Exception e) { e.printStackTrace(); } return upload; }
我的个人网站 : zegoto.cn 欢迎来信 希望能帮到你