struts2上傳與下載

上傳

在Action裏

private File abcFile;
private String abcFileName;//這兩個參數是可選的

private String abcContentType;//這兩個參數是可選的

然後生成set方法

當表單提交之後 如果有上傳文件的話 上面三個值就已經自動設置好了

如果有多個文件 假設都是 <input type="file" name="abc" />

那隻要將上面3個都改成數組或List就行了

關於上傳文件類型 和大小限制等 參見fileUpload攔截器

<action name="sc" class="ssh.action.UploadAction" method="m1">
<result>/success.jsp</result>
<result name="input">/upload.jsp</result>
<interceptor-ref name="defaultStack">
<param name="fileUpload.maximumSize">5242880</param><!-- 5MB --> 單個文件最大5MB
<!-- <param name="fileUpload.allowedTypes"></param> -->
<param name="fileUpload.allowedExtensions">zip,rar</param>//後綴名只能是zip或rar
</interceptor-ref>

</action>

另外還需要再struts.xml裏

<constant name="struts.multipart.maxSize" value="20971520"/>//總的大小不超過20MB


upload.jsp 片段

<s:debug/>
<s:fielderror value="abc"/>
<form action="sc" method="post" enctype="multipart/form-data">
<input type="file" name="abc" />
<input type="file" name="abc" />
<input type="file" name="abc" />
<input type="file" name="abc" />
<input type="file" name="abc" />
<input type="submit" value="submit" />
</form>

Action 片段

public String m1() {
if (abc != null) {
for (int i = 0; i < abc.length; ++i) {//可以發現實際提交了幾個 長度就爲幾
System.out.println( abc[i].getName() + " " + abcFileName[i] + " " + abcContentType[i] );
}
}
return SUCCESS;
}


下載

假設在你的Action中有一個叫
abcStream的屬性 (有getAbcStream()方法 返回InputStream)


在配置文件裏
<action name="download" class="xxx" method="yyy">
<result type="stream">//這裏有部分值是寫死的 可以考慮用ognl表達式動態設置
<param name="contentType">image/jpeg</param>//表明打開/下載的是圖片
<param name="inputName">abcStream</param>//寫流的名字

<!-- 如果是inline就是在瀏覽器中打開 -->
<param name="contentDisposition">attachment;filename="xxx.jpg"</param>//提示瀏覽器打開下載窗口,文件名是xxx.jpg

<param name="bufferSize">1024</param>//緩存大小 默認就是1024 不設置也行
<param name="contentLength ">${contentLength}</param>//內容的長度 這裏使用了ognl表達式 所以在相應的Action裏有一個contentLength屬性
//如果不設置這個值,則下載的時候看不到文件的總大小
</result>
</action>


如果下載文件名有中文 則需要 <param name="contentDisposition">attachment;filename="${@java.net.URLEncoder@encode('測試.jpg','utf-8')}"</param>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章