標籤:multipart this tty 功能 erp filename 目錄 com tac
檔案上傳
1.struts2中檔案上傳介紹
struts2檔案上傳需要使用apache提供的檔案上傳組件(commons-fileupload.jar和commons-io.jar)。
struts2檔案上傳的核心是通過fileupload攔截器實現的。
2.如何?檔案上傳
1>.添加commons-fileupload和commons-io包
2>.在jsp頁面做如下配置
將form的method屬性值設定為post
給form標記添加屬性enctype="multipart/form-data"(讓提交的表單資料,以流的形式提交)
3>.在action類中添加如下屬性,並添加get|set方法
private File xxx;
private String xxxFileName;
private String xxxContentType;
注意:xxx指代<input type="file">檔案域的name值
struts2的檔案上傳功能,是將用戶端上傳的檔案儲存到一個臨時目錄,我們要做的事情,就是將臨時目錄中的檔案儲存到指定目錄。
檔案下載
在struts2中如何?檔案下載
1.添加一個檔案下載的action類
public class DownloadAction{
private InputStream logoStream;
public InputStream getLogoStream(){
try{
this.fileName = brand.getLogoUrl();
//擷取被下載的檔案的絕對路徑
String filePath = ServletActionContext.getRequest().getServletContext().getRealPath(brand.getLogoUrl());
System.out.println(filePath);
//讀取被下載的檔案
logoStream = new FileInputStream(filePath);
return logoStream;
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}
}
2.在該類中添加一個action方法,返回success
public class DownloadAction{
public String download(){
return "success";
}
}
3.在struts.xml中配置該action,並且result的結果類型為stream
<action name="download" class="...DownloadAction" method="download">
<result name="success" type="stream">
</result>
</action>
4.在result中設定參數inputName,該參數的值必須為action類中的一個資料類型為InputStream的屬性。
<action name="download" class="...DownloadAction" method="download">
<result name="success" type="stream">
<param name="inputName">logoStream</param>
</result>
</action>
5.控制下載檔案的檔案名稱:在result中添加參數:contentDisposition
<action name="download" class="...DownloadAction" method="download">
<result name="success" type="stream">
<param name="inputName">logoStream</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
</result>
</action>
注意:${fileName} 中的fileName為action類中的屬性
6.控制檔案的類型:在result中添加參數:contentType
contentType:
word : application/msword
excel : application/vnd.ms-excel
ppt : application/vnd.ms-powerpoint
html : text/html
文字檔 : text/plain
可執行檔 : application/octet-stream
<action name="download" class="...DownloadAction" method="download">
<result name="success" type="stream">
<param name="inputName">logoStream</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="contentType">application/octet-stream</param>
</result>
</action>
struts2檔案上傳下載