步骤为:
1、判断系统是否为windows;
2、设置上传文件路径
代码如下:
/**
* true 为windosw操作系统
* false 为其他操作系统
* @return
*
*/
public static boolean checkSystem(){
Properties prop = System.getProperties();
String os = prop.getProperty("os.name");
if(os.startsWith("win") || os.startsWith("Win")){
return true;
}else{
return false;
}
}
/**
* 创建文件夹,并上传文件
* @param rootPath 根目录
* @param path 大文件名
* @param uploadProductFile 上传的文件
* @param fileName 上传的文件名
*/
public static void createFileMdir(String rootPath,String path,File uploadProductFile,String fileName){
try {
String pathMdir = "";
String pathMdirName = "";
if(System.getProperty("os.name").toUpperCase().indexOf("WINDOWS")!=-1){
pathMdir = rootPath+path+"\\";
if(fileName!=null &&!fileName.equals("")){
pathMdirName = rootPath+path+"\\"+fileName;
}
}else{
pathMdir = rootPath+"/"+path+"/";
if(fileName!=null &&!fileName.equals("")){
pathMdirName = rootPath+"/"+path+"/"+fileName;
}
}
File mdri = new File(pathMdir);
if(!mdri.isDirectory()){
mdri.mkdir();
}
if(uploadProductFile.exists()){
FileUtils.copyFile(uploadProductFile, new File(pathMdirName));
}
} catch (IOException e) {
e.printStackTrace();
}
}
String realPath= getRequest().getSession().getServletContext().getRealPath("/");
调用:SystemUtil.createFileMdir(realPath,"product_pic",new File(""),"");
可以使用File.separator自动获取系统路径,无需判断系统
上边代码可以简化为
public static void createFileMdir(String rootPath,String path,File uploadProductFile,String fileName){
try {
String pathMdir = "";
String pathMdirName = "";
String fName = File.separator;
if(fileName!=null &&!fileName.equals("")){
pathMdirName = rootPath+fName+path+fName+fileName;
}
File mdri = new File(pathMdir);
if(!mdri.isDirectory()){
mdri.mkdir();
}
if(uploadProductFile.exists()){
FileUtils.copyFile(uploadProductFile, new File(pathMdirName));
}
} catch (IOException e) {
e.printStackTrace();
}
}