单个文件上传
【第一步】
前台页面:
【第二步】
在struts中设置:
<action name="errorexe"class="com.aaa.action.ExceAction"
method="errorexe">
<interceptor-ref name="fileUpload">
<param name="allowedExtensions">.bmp,.gif,.jpg</param>
<param name="maximumSize">104857600</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result>/index.jsp</result>
</action>
【第三步】
写action
Action的属性值:
private File photo;
private String photoFileName;
private String title;
Action的方法:
public String errorexe() {
System.out.println(photo);
try {
//InputStream 字节
//reader 字符
InputStream is = new FileInputStream(photo);//输入流
byte[] b = new byte[1000];//字节数组
int n = -1;//每次读出的字节个数
String path = ServletActionContext.getRequest().getRealPath("/");
String filename = "file/" + photoFileName;
photoFileName = filename;
OutputStream os = new FileOutputStream(path + filename);//输出流
while ((n = is.read(b)) > 0) {//循环读取文件
os.write(b, 0, n);//写文件,从B的第0个下标开始写,直到读取的个数N
}
os.flush();//刷新缓存(输出流)
os.close();//关闭并刷新缓存(输出流)
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
多个文件上传
【第一步】
前台页面:
【第二步】
在struts中设置:
<action name="errorexe"class="com.aaa.action.ExceAction"
method="errorexe">
<interceptor-ref name="fileUpload">
<param name="allowedExtensions">.bmp,.gif,.jpg</param>
<param name="maximumSize">104857600</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result>/index.jsp</result>
</action>
【第三步】
写action
属性设置:
写方法:
总结
多文件上传和单文件上传本质上是一样的,只是多文件上传时,需要对文件进行遍历