1. 程式人生 > >struts2檔案上傳,看到書上講的action類的執行方法不是execute而是upload,不解,故搜之

struts2檔案上傳,看到書上講的action類的執行方法不是execute而是upload,不解,故搜之

package com.ljq.action; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; @SuppressWarnings("serial") publicclass UploadAction2 extends ActionSupport {
// 封裝上傳檔案域的屬性private File image; // 封裝上傳檔案型別的屬性private String imageContentType; // 封裝上傳檔名的屬性private String imageFileName; // 接受依賴注入的屬性private String savePath; @Override public String execute() { FileOutputStream fos =null; FileInputStream fis =null; try {
// 建立檔案輸出流 System.out.println(getSavePath()); fos =new FileOutputStream(getSavePath() +"\\"+ getImageFileName()); // 建立檔案上傳流 fis =new FileInputStream(getImage()); byte[] buffer =newbyte[1024]; int len =0; while ((len = fis.read(buffer))
>0) { fos.write(buffer, 0, len); } } catch (Exception e) { System.out.println("檔案上傳失敗"); e.printStackTrace(); } finally { close(fos, fis); } return SUCCESS; } /** * 返回上傳檔案的儲存位置 * * @return*/public String getSavePath() throws Exception{ return ServletActionContext.getServletContext().getRealPath(savePath); } publicvoid setSavePath(String savePath) { this.savePath = savePath; } public File getImage() { return image; } publicvoid setImage(File image) { this.image = image; } public String getImageContentType() { return imageContentType; } publicvoid setImageContentType(String imageContentType) { this.imageContentType = imageContentType; } public String getImageFileName() { return imageFileName; } publicvoid setImageFileName(String imageFileName) { this.imageFileName = imageFileName; } privatevoid close(FileOutputStream fos, FileInputStream fis) { if (fis !=null) { try { fis.close(); } catch (IOException e) { System.out.println("FileInputStream關閉失敗"); e.printStackTrace(); } } if (fos !=null) { try { fos.close(); } catch (IOException e) { System.out.println("FileOutputStream關閉失敗"); e.printStackTrace(); } } } }