struts2 文件上传下载

1.实现 struts2 文件上传,下载 功能

     最近在做OA项目的过程中需要做一个信访登记里面需要用到一个文件上传下载的功能,  页面如下:

struts2 文件上传下载
         

实现思路:

       当点击确定的时候,同时进行文件上传和保存当前的这条数据,文件上传到web项目的根指目录的指定文件夹,并且保证每次上传的文件名称是唯一。

      首先获得上传的文件类型,例如:上传一个名为1232131.txt的文本文件, 则获取.txt后缀名,然后随机生成一个流水号, 用流水号+文件的后缀 拼成一个新的文件名,这样就能保存文件名的唯一, 并且将文件全名存入数据库表中的某个字段,这样可以方便文件下载操作,





1.首先在action.xml 中需要配置如下几个参数


<action name="person" class="xfpersonAction"  >
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">fileInputStream</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="bufferSize">102400000</param>
</result>                
</action>

在action中配置<result></result>节点 ,以及<param></param> 子节点,如下图:struts2 文件上传下载


文件上传关键代码 ,如图:struts2 文件上传下载

if (file != null) {
String root = ServletActionContext.getServletContext().getRealPath("/attachFiles");
InputStream is = new FileInputStream(file);
String ffHouZhui = fileFileName.substring(fileFileName.length() - fileFileName.lastIndexOf("."),
fileFileName.length());
System.out.println("后缀" + ffHouZhui);
// 组成一个新的文件名称
FilenewName = Getnum() + "." + ffHouZhui;
// 创建一个新的File
OutputStream os = new FileOutputStream(new File(root, FilenewName));


byte[] buffer = new byte[500];
int length = 0;
try {
while (-1 != (length = is.read(buffer, 0, buffer.length))) {
os.write(buffer);
}
os.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

   

 

  struts2 文件上传下载

  如上图, 前台 <input  type="file" name="file"> 文件控件定义的name=file,所以后台这边定义接收也应该叫file,如下图:

struts2 文件上传下载




定义一个随机数,组成唯一文件名,随机数的方法如下,很简单

struts2 文件上传下载



实现文件下载,如图:


struts2 文件上传下载


这里定义的fileInputStream 名称要和

<param name="inputName">fileInputStream</param>中的fileInputStream名字一样才行,否则不行

struts2 文件上传下载

下载的链接如下图:

struts2 文件上传下载


action 的name 加上filename即可,