struts2 文件上传于下载
<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_*" 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";
}