//获取该目录下的文件D:\java\oa\target\classes\doc (对应的是resources/doc下面的文件),如下:
String docPath=ResourceUtils.getFile("classpath:doc").getPath();
注释:
1、docPath为存储到项目中的指定路径。
2、避免文件名重复被覆盖,上传文件到项目中文件路径时,在文件名后面加上随机数,调用ContentUtil类中的方法ContentUtil.randomGen(6);
public static File transferTo(MultipartFile file, String docPath) throws IOException {
String fileName= StringUtils.isEmpty(file.getOriginalFilename())?file.getName()+ContentUtil.randomGen(6):file.getOriginalFilename()+ContentUtil.randomGen(6);
// 转存文件
File distFile = new File(docPath);
if (!distFile.isDirectory()) {
//如果路径不存在就创建
distFile.mkdirs();
}
//上传文件
File pushFile = new File(docPath+ fileName);
file.transferTo(pushFile);//转存文件到指定路径,如果文件名重复的话,将会覆盖掉之前的文件
return pushFile;
}
ContentUtil类中的方法代码如下:
public static String randomGen(Integer length){
char[] chars={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9'};
Random random=new Random();
int count=0;
StringBuilder sb=new StringBuilder();//动态字符串
while(true){
char c=chars[random.nextInt(chars.length)];
if(sb.indexOf(c+"")==-1){
sb.append(c);
count++;
if(count==length){
break;
}
}
}
return sb.toString();
}