<!-- 配置文件设置 --> <action name="fileupload_*" class="FileuploadAct" method="{1}"> <!-- 若上传的文件不符合要求则返回input --> <result name="input">/error.jsp</result> <!-- 限制上传的文件的大小,在struts-default.xml中我们可能找到一个fileUpload拦截器 --> <interceptor-ref name="fileUpload"> <!-- 单位为字节,这里为116528750 大约为100M这里的大小是指每个文件上传的大小,若多个文件上传指每一个文件的大小 --> <param name="maximumSize">116528750</param> <!-- 指定文件上传的类型,在X:\Program Files\Apache Software Foundation\Tomcat 6.0\conf\web.xml中Tomcat提定所有文件类型 --> </interceptor-ref> <!-- 加上默认拦截器 --> <interceptor-ref name="defaultStack"></interceptor-ref> </action>
<form action="/user/user.action" method="post" id="basicForm" name="basicForm" enctype="multipart/form-data">
<input type="file" name="files"/>
<input type="file" name="files"/>
</form>
Action 中处理
// 文件
private File[] files;
// 文件名字
private String[] filesFileName;
// 文件类型
private String[] filesContentType;
循环files执行以下的方法:
/**
* 保存文件
*
* @param file
* @param saveDir
* @param saveDir2
* @return
*/
private String saveFile(File file, String suffix, String saveDir) {
File saveDirFile = new File(saveDir);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
Random rm = new Random();
String newFileName = System.currentTimeMillis() + rm.nextInt(1000) + suffix ;
try {
bis = new BufferedInputStream(new FileInputStream(file));
bos = new BufferedOutputStream(new FileOutputStream(new File(
saveDir, newFileName)));
byte[] bs = new byte[1024];
int len;
while ((len = bis.read(bs, 0, 1024)) > 0) {
bos.write(bs, 0, len);
}
bis.close();
bos.close();
file.delete();
return newFileName;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
=--------------------下载----------
1 配置文件
<!-- download --> <action name="download_*" class="com.userAct" method="{1}"> <result name="success" type="stream"> <!-- 指定下载文件的内容类型,text/plain是默认类型 --> <param name="contentType">application/octet-stream</param> <!-- inputName默认值是inputStream,如果action中用于读取下载文件内容的属性名是inputStream,那么可以省略这个参数 --> <param name="inputName">inputStream</param> <!--动态获取文件名,从Action中的取得filename--> <param name="contentDisposition"> attachment;filename="${fileName}" </param> <param name="bufferSize">4096</param> </result> </action>
2 Action中处理
private InputStream inputStream;
public String downLoadFile(){
//查询出文件的路径filepath
fileName="下载文件的真实名称";
try {
inputStream = new FileInputStream( new File(filepath ));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return "success";
}