1.文件上传
1.1单文件上传
Action类: FileUpLoadAction.java
public class FileUpLoadAction{
//getter和Setter方法自己写
private File img;
private String imgFileName; //必须为文件名+FileName
public String execute() {
if (img!=null) {
try {
//文件上传路径,这里是后台的相对路径
String path =
ServletActionContext.getServletContext().getRealPath("/images");
File destFile = new File(path, imgFileName);
FileUtils.copyFile(img, destFile);
return "success";
} catch (IOException e) {
e.printStackTrace();
}
}
return "fail";
}
}
struts.xml配置文件:
<struts>
<!--name中的是固定的,上传文件的 默认大小为2M(2097152) -->
<constant name="struts.multipart.maxSize" value="209715200"></constant>
<package name="default" namespace="/" extends="struts-default">
<action name="upload" class="com.action.FileUpLoadAction">
<result>/welcome.jsp</result>
<result name="fail">/index.jsp</result>
<!-- 设置文件上传的格式 -->
<interceptor-ref name="defaultStack">
<param name="fileUpload.allowedExtensions">gif,jpeg,jpg,png</param>
</interceptor-ref>
</action>
</package>
</struts>
inrdex.jsp页面:
<s:form action ="upload" method="post" enctype="multipart/form-data">
<s:file name="img" label="选择文件"></s:file>
<s:submit value="上传"></s:submit>
</s:form>
1.2多文件上传
多文件上传,与单文件上传的不同之处在于,Action类中的成员变量定义为数组,遍历上传到服务器,struts.xml配置文件的内容不变。 在这里只展示核心代码:
Action类: FileUpLoadAction.java
//imgs,imgsFileName都是数组
public String execute() {
if (imgs!=null) {
String path =
ServletActionContext.getServletContext().getRealPath("images");
for (int i = 0; i < imgs.length; i++) {
try {
System.out.println(path);
File destFile = new File(path, imgsFileName[i]);
FileUtils.copyFile(imgs[i], destFile);
} catch (IOException e) {
e.printStackTrace();
}
}
return "success";
}
return "fail";
}
index.jsp页面:
<s:form action ="upload" method="post" enctype="multipart/form-data">
<s:file name="imgs" label="选择文件1"></s:file>
<s:file name="imgs" label="选择文件2"></s:file>
<s:file name="imgs" label="选择文件3"></s:file>
<s:submit value="上传"></s:submit>
</s:form>
2.文件下载
文件下载相比上传简单,只展示核心代码:
Action类:DownloadAction.java:
public class DownloadAction {
//getter和setter方法这里就不再写了
private InputStream is; //声明流
private String fileName; //文件名
public String execute() throws Exception {
//fileName="黑执事1.jpg";
fileName="2.jpg";
//获取要下载的文件流
is=ServletActionContext.getServletContext().getResourceAsStream("/images/"+fileName);
fileName="黑执事2.jpg";
//解决乱码问题
byte[] bytes = fileName.getBytes("GBK"); //这里看你用的是哪种编码格式了
fileName = new String(bytes,"iso-8859-1");
return "success";
}
}
配置文件:struts.xml
<action name="download" class="com.action.DownloadAction">
<result type="stream">
<param name="contentDisposition">
attachment;filename=${fileName }
</param>
<param name="inputName">is</param>
<!-- 默认为 <param name="inputName">inputStream</param>-->
</result>
</action>
index.jsp页面:
<body>
图片下载<br/>
<a href="download.action">黑执事</a>
</body>