1. 程式人生 > 實用技巧 >java 上傳圖片到Tomcat的webapps目錄下

java 上傳圖片到Tomcat的webapps目錄下

java 上傳圖片到Tomcat的webapps目錄下
`

  // 圖片上傳地址(Linux)
  //private static String IMAGE_UPLOAD_URL = /usr/local/apache-tomcat-picture/webapps
  // 圖片上傳地址(window)
  private static String IMAGE_UPLOAD_URL = D:/apache-tomcat-picture/webapps

/** 上傳圖片到Tomcat的webapps目錄下 **/
public static String uploadFileInTomcatWebapps(MultipartFile file) throws IllegalStateException, IOException{
	if(null != file){
		// 獲取上傳檔案的原始名稱
		String originalFilename = file.getOriginalFilename();
		if (null != originalFilename && originalFilename.length() > 0) {
			// 生成新的圖片名稱
			String newFileName = genImageName() + originalFilename.substring(originalFilename.lastIndexOf("."));				
			// 獲取Tomcat伺服器所在的路徑
			String tomcat_path = System.getProperty( "user.dir" );
			System.out.println("Tomcat伺服器所在的路徑: "+tomcat_path);
			// 獲取Tomcat伺服器所在路徑的最後一個檔案目錄
			String bin_path = tomcat_path.substring(tomcat_path.lastIndexOf("/")+1,tomcat_path.length());
			System.out.println("Tomcat伺服器所在路徑的最後一個檔案目錄: "+bin_path);
			String pic_path = "";
			// 判斷最後一個檔案目錄是否為bin目錄
			if(("bin").equals(bin_path)){ 
				// 獲取儲存上傳圖片的檔案路徑
				pic_path = tomcat_path.substring(0,System.getProperty( "user.dir" ).lastIndexOf("/")) +"/webapps"+"/images/";
			}else{					
				pic_path = IMAGE_UPLOAD_URL+"/images/";
			}
			// 設定檔案儲存路徑(檔案存放按日期存放)
			String datePath = new DateTime().toString("/yyyy/MM/dd"); 
			File newFileDir = new File(pic_path+datePath);
			//如果不存在 則建立
            if (!newFileDir.exists()) {	            	
            	newFileDir.mkdirs();	           
            }
			// 將記憶體中的資料寫入磁碟
            String savePath = newFileDir +"/" + newFileName;
            System.out.println("上傳圖片的路徑:" + savePath);
			file.transferTo(new File(savePath));
			// 返回路徑
			String url = "/images"+datePath+"/"+newFileName;				
			return url;
		}
	}
	return null;
}

/** 圖片名生成 **/
public static String genImageName() {
	//取當前時間的長整形值包含毫秒
	long millis = System.currentTimeMillis();
	//加上三位隨機數
	Random random = new Random();
	int end3 = random.nextInt(999);
	//如果不足三位前面補0
	String str = millis + String.format("%03d", end3);		
	return str;
}

`