Struts2上传文件判断系统并上传(windows or liunx)

步骤为:

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();
		}
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值