基本思路在於,配置路徑,然后用java I/O的api將圖片上傳到該目錄下。
String photoPath =
ServletActionContext.getServletContext().getRealPath("/user/photo/" + username);
這句是獲取服務器下的目錄+username
而username通過session獲取。
這是一個圖片上傳action的方法:
public String execute() throws Exception { //獲得username Map session = ServletActionContext.getContext().getSession(); String username = (String) session.get("username"); //創建一個輸入流 InputStream is = new FileInputStream(myFile); //設置文件保存目錄 String photoPath = ServletActionContext.getServletContext().getRealPath("/user/photo/" + username); File filePhotoPath = new File(photoPath); if(!filePhotoPath.isDirectory()) { filePhotoPath.mkdir(); } //解決中文文件名問題 String extension = FilenameUtils.getExtension(this.getMyFileFileName()); String filename = UUID.randomUUID().toString() + "."+ extension; //設置目標文件 File tofile = new File(photoPath,filename); //使用輸出流來包裝目標文件 OutputStream os = new FileOutputStream(tofile); byte[] buffer = new byte[1024]; int length = 0; while((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } //關閉輸入流 is.close(); //關閉輸出流 os.close(); return this.SUCCESS; }