Struts2的一個和多個檔案上傳的實現
阿新 • • 發佈:2019-01-22
在Struts2中,上傳檔案時,只要使用java.io.File類來描述上傳檔案即可,比直接使用Commons-FileUpload元件要簡單的多。
上傳單個檔案:如果上傳的是單個檔案,則在Action類中定義一個File型別的變數。該變數的名字與JSP頁面上的<input />標籤的name屬性相對應,只有這樣Struts2才能使客戶端上傳的檔案自動與Action類中的相應的屬性進行關聯處理。
上傳多個檔案:如果上傳的是多個檔案,這時在JSP頁面中的所有的<input type="file" name="upload" />標籤的name屬性值都必須相同,這時Action中相對應的屬性就要使用List或File[]用來表示多個檔案的資訊。
儲存檔案相關屬性的變數設定如下:
private List<File> upload; //儲存上傳的檔案 private List<String> uploadContentType; //儲存上傳的檔案型別 private List<String> uploadFileName; //儲存上傳的檔名
以下是一個使用Struts 2上傳多個檔案的例子,把上傳的檔案重新用生成的隨機數命名:
Struts2上傳檔案相關程式碼public class UploadFilesAction extends ActionSupport { private List upload; private List uploadContentType; private List uploadFileName; private String uploadPath; private String result; private boolean success; private String msg; public boolean isSuccess() { return success; } public String getMsg() { return msg; } public String getResult() { return result; } public void setUpload(List upload) { this.upload = upload; } public void setUploadContentType(List uploadContentType) { this.uploadContentType = uploadContentType; } public void setUploadFileName(List uploadFileName) { this.uploadFileName = uploadFileName; } public void setUploadPath(String uploadPath) { this.uploadPath = uploadPath; } public String execute() throws Exception { for (int i = 0; i < uploadFileName.size(); i++) { Random random = new Random(); String filename = uploadFileName.get(i); //把上傳的檔案用生成的隨機數重新命名 //並判斷生成的檔名是否已經存在 //如果存在,則繼續生成隨機數命名,直到找打還沒使用的隨機數為止 filename = uploadPath + random.nextLong() + filename.substring(filename.lastIndexOf(".")); while (new File(filename).exists()) { filename = uploadPath + random.nextLong() + filename.substring(filename.lastIndexOf(".")); } FileOutputStream fos = new FileOutputStream(filename); InputStream is = new FileInputStream(upload.get(i)); byte[] buffer = new byte[8192]; int count = 0; while ((count = is.read(buffer)) > 0) { fos.write(buffer, 0, count); } fos.close(); is.close(); } success=true; msg = "檔案上傳成功!"; return "result"; } }
<package name="struts2" namespace="/" extends="struts-default"> <action name="uploadFiles" class="uploadtest.actions.UploadFilesAction"> <result name="result">/WEB-INF/result.jsp</result> <param name="uploadPath">D:\UploadFiles\</param> </action> </package>