// 文件上傳需要的三個屬性:
private File upload;
private String uploadFileName;
@SuppressWarnings("unused")
private String uploadContentType;
import org.apache.commons.io.FileUtils;
// 保存商品的方法:
public String save() throws IOException {
// 將提交的數據添加到數據庫中.
product.setPdate(new Date());
// product.setImage(image);
if(upload != null){
// 將商品圖片上傳到服務器上.
// 獲得上傳圖片的服務器端路徑.
String path = ServletActionContext.getServletContext().getRealPath(
"/products");
// 創建文件類型對象:
File diskFile = new File(path + "//" + uploadFileName);
// 文件上傳:
FileUtils.copyFile(upload, diskFile);
product.setImage("products/" + uploadFileName);
}
productService.save(product);
return "saveSuccess";
}
// 修改商品的方法
public String update() throws IOException {
// 將信息修改到數據庫
product.setPdate(new Date());
// 上傳:
if(upload != null ){
String delPath = ServletActionContext.getServletContext().getRealPath(
"/" + product.getImage());
File file = new File(delPath);
file.delete();
// 獲得上傳圖片的服務器端路徑.
String path = ServletActionContext.getServletContext().getRealPath(
"/products");
// 創建文件類型對象:
File diskFile = new File(path + "//" + uploadFileName);
// 文件上傳:
FileUtils.copyFile(upload, diskFile);
product.setImage("products/" + uploadFileName);
}
productService.update(product);
// 頁面跳轉
return "updateSuccess";
}