java中struts2實(shí)現(xiàn)文件上傳下載功能
先談一談struts2實(shí)現(xiàn)文件的上傳和下載實(shí)例實(shí)現(xiàn)的原理:
Struts 2是通過(guò)Commons FileUpload文件上傳。
Commons FileUpload通過(guò)將HTTP的數(shù)據(jù)保存到臨時(shí)文件夾,然后Struts使用fileUpload攔截器將文件綁定到Action的實(shí)例中。從而我們就能夠以本地文件方式的操作瀏覽器上傳的文件。
具體實(shí)現(xiàn):
一、創(chuàng)建index.jsp頁(yè)面
<body> <s:form action="upload" method="post" theme="simple" enctype="multipart/form-data"> <table align="center" width="50%" border="1"> <tr> <td>選擇上傳文件</td> <td id="more"> <s:file name="file"></s:file> <input type="button" value="Add More.." onclick="addMore()"> </td> </tr> <tr> <td><s:submit type="button" value="submit" onclick="return checkf()"/></td> <td><s:reset value="reset "></s:reset></td> </tr> </table> <table align="center" width="50%" border="1"> <tr> <td>測(cè)試.txt</td> <td> <a href="<s:url value='download.action'><s:param name='fileName'>測(cè)試.txt</s:param> </s:url>">下載</a> </td> </tr> </table> </s:form> </body>
創(chuàng)建result.jsp頁(yè)面
<body> <s:form> <div style="border:1px solid black">成功上傳的文件:<br> <ul style="list-style-type:decimal"> <s:iterator value="#request.fileName" id="file" status="status"> <li><s:property/> </li> </s:iterator> </ul> </div> </s:form> </body>
當(dāng)然別忘了在每個(gè)頁(yè)面上都添加上struts2 標(biāo)簽引用<%@taglib prefix="s" uri="/struts-tags" %>
二、創(chuàng)建updown.js文件,在index.jsp中引用
function checkf(){
var files = document.getElementsByName("file");
if(files[0].value.length!=0){
return true;
}else{
alert("請(qǐng)選擇文件");
return false;
}
}
function addMore()
{
var td = document.getElementById("more");
var br = document.createElement("br");
var input = document.createElement("input");
var button = document.createElement("input");
input.type = "file";
input.name = "file";
button.type = "button";
button.value = "Remove";
button.onclick = function()
{
td.removeChild(br);
td.removeChild(input);
td.removeChild(button);
}
td.appendChild(br);
td.appendChild(input);
td.appendChild(button);
}
三、創(chuàng)建upDownloadAction.java
package com.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
public class UpDownloadAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private List<File> file;// 對(duì)應(yīng)jsp中file標(biāo)簽
private List<String> fileFileName;//
private List<String> fileContentType;//
private String fileName;//獲得jsp中pram參數(shù)
@SuppressWarnings("deprecation")
// 文件上傳
public String uploadFiile() throws Exception {
String root = ServletActionContext.getServletContext().getRealPath(
"/upload");// 上傳路徑
System.out.println(root);
InputStream inputStream;
File destFile;
OutputStream os;
for (int i = 0; i < file.size(); i++) {
inputStream = new FileInputStream(file.get(i));
destFile = new File(root, this.getFileFileName().get(i));
os = new FileOutputStream(destFile);
byte[] buffer = new byte[400];
int length = 0;
while ((length = inputStream.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
inputStream.close();
os.close();
}
HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("fileName", fileFileName);
return SUCCESS;
}
// 文件下載
public InputStream getDownloadFile() throws FileNotFoundException,
UnsupportedEncodingException {
System.out.println(getFileName());
// 如果下載文件名為中文,進(jìn)行字符編碼轉(zhuǎn)換
ServletActionContext.getResponse().setHeader("Content-Disposition","attachment;fileName="
+ java.net.URLEncoder.encode(fileName, "UTF-8"));
InputStream inputStream = new FileInputStream("F:/" //使用絕對(duì)路徑 ,從該路徑下載“測(cè)試.txt"文件
+ this.getFileName());
System.out.println(inputStream);
return inputStream;
}
// 下載
public String downloadFile() throws Exception {
return SUCCESS;
}
public String getFileName() throws UnsupportedEncodingException {
return fileName;
}
public void setFileName(String fileName)
throws UnsupportedEncodingException {
this.fileName = new String(fileName.getBytes("ISO8859-1"), "utf-8");
}
}
注:屬性的 get和set方法已省略。
四、最后是配置文件
1、web.xml配置
<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2、struts.xml配置
<struts>
<constant name="struts.i18n.encoding" value="utf-8"></constant>
<constant name="struts.multipart.saveDir" value="f:\"></constant>
<package name="struts2" extends="struts-default">
<action name="upload" class="com.action.UpDownloadAction" method="uploadFiile">
<result name="success">/jsp/result.jsp</result>
<interceptor-ref name="fileUpload">
<!--maximumSize (可選) - 這個(gè)攔截器允許的上傳到action中的文件最大長(zhǎng)度(以byte為單位).
注意這個(gè)參數(shù)和在webwork.properties中定義的屬性沒(méi)有關(guān)系,默認(rèn)2MB-->
<param name="maximumSize">409600</param>
<!--allowedTypes (可選) - 以逗號(hào)分割的contentType類型列表(例如text/html),
這些列表是這個(gè)攔截器允許的可以傳到action中的contentType.如果沒(méi)有指定就是允許任何上傳類型.-->
<param name="allowedTypes">
text/plain
</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
<action name="download" class="com.action.UpDownloadAction" method="downloadFile" >
<result name="success" type="stream">
<!--指定文件下載類型 application/octet-stream默認(rèn)值可以下載所有類型 -->
<param name="contentType">
application/txt;
</param>
<!-- 指定下載的文件名和顯示方式 ,但注意中文名的亂碼問(wèn)題,解決辦法是:進(jìn)行編碼處理-->
<!--contentDisposition是文件下載的處理方式,包括內(nèi)聯(lián)(inline)和附件(attachment),
默認(rèn)是inline, 使用附件時(shí)這樣配置:attachment;filename="文件名" 。-->
<param name="contentDisposition">
attachment;filename="${fileName}"
</param>
<!--由getDownloadFile()方法獲得inputStream-->
<param name="inputName">downloadFile</param>
<!-- 指定下載文件的緩存大小-->
<param name="bufferSize">2048</param>
</result>
</action>
</package>
</struts>
一個(gè)簡(jiǎn)單的Struts2多文件上傳和單文件下載就實(shí)現(xiàn)了。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。
- struts2實(shí)現(xiàn)簡(jiǎn)單文件下載功能
- JSP開(kāi)發(fā)之Struts2實(shí)現(xiàn)下載功能的實(shí)例
- struts2實(shí)現(xiàn)文件下載功能
- java中Struts2 的文件上傳和下載示例
- Struts2實(shí)現(xiàn)文件下載功能代碼分享(文件名中文轉(zhuǎn)碼)
- java中struts2實(shí)現(xiàn)簡(jiǎn)單的文件上傳與下載
- JavaWeb中struts2實(shí)現(xiàn)文件上傳下載功能實(shí)例解析
- JavaEE中struts2實(shí)現(xiàn)文件上傳下載功能實(shí)例解析
- java中struts2實(shí)現(xiàn)文件上傳下載功能實(shí)例解析
- struts2實(shí)現(xiàn)文件下載功能
相關(guān)文章
Spring?cloud負(fù)載均衡@LoadBalanced?&?LoadBalancerClient
由于Spring?cloud2020之后移除了Ribbon,直接使用Spring?Cloud?LoadBalancer作為客戶端負(fù)載均衡組件,我們討論Spring負(fù)載均衡以Spring?Cloud2020之后版本為主,學(xué)習(xí)Spring?Cloud?LoadBalance2023-11-11
Spring Aop之AspectJ注解配置實(shí)現(xiàn)日志管理的方法
下面小編就為大家分享一篇Spring Aop之AspectJ注解配置實(shí)現(xiàn)日志管理的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
java.lang.UnsatisfiedLinkError: %1 不是有效的Win32應(yīng)用程序錯(cuò)誤解決
這篇文章主要給大家介紹了關(guān)于java.lang.UnsatisfiedLinkError: %1 不是有效的Win32應(yīng)用程序錯(cuò)誤的解決方法,文中介紹的非常詳細(xì),需要的朋友們可以參考學(xué)習(xí),下面來(lái)一起看看吧。2017-03-03
SpringBoot整合MybatisSQL過(guò)濾@Intercepts的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot整合MybatisSQL過(guò)濾@Intercepts的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
SpringBoot如何優(yōu)雅的處理重復(fù)請(qǐng)求
對(duì)于一些用戶請(qǐng)求,在某些情況下是可能重復(fù)發(fā)送的,如果是查詢類操作并無(wú)大礙,但其中有些是涉及寫(xiě)入操作的,一旦重復(fù)了,可能會(huì)導(dǎo)致很?chē)?yán)重的后果,所以本文給大家介紹了SpringBoot優(yōu)雅的處理重復(fù)請(qǐng)求的方法,需要的朋友可以參考下2023-12-12
Java?Maven構(gòu)建工具中mvnd和Gradle誰(shuí)更快
這篇文章主要介紹了Java?Maven構(gòu)建工具中mvnd和Gradle誰(shuí)更快,mvnd?是?Maven?Daemon?的縮寫(xiě)?,翻譯成中文就是?Maven?守護(hù)進(jìn)程,下文更多相關(guān)資料,需要的小伙伴可以參考一下2022-05-05

