Struts2实现上传文件

来源:互联网 发布:不动产静态投资 软件 编辑:程序博客网 时间:2024/03/29 13:40

需用到两个包

commons-io-2.0.1.jar、commons-fileupload-1.3.jar

form表单必须加enctype="multipart/form-data"属性

<form action="Test/uploadAction" method="post" enctype="multipart/form-data">    <input type="file" name="upload"/>    <input type="submit" value="上传"/></form>


struts2核心配置文件

<!-- 配置信息 --><package name="Test" extends="struts-default" namespace="/Test"><!-- 配置默认类 --><default-class-ref class="com.erp.test.TestAction"></default-class-ref><!-- 配置action --><action name="uploadAction" method="upload"><result name="success">/upload.jsp</result></action></package>

后台实现上传模块

/* * 这三个属性必须有 * *///接收前台传来的文件private File upload;//接收前台处理后传来的文件类型private String uploadContentType;//接收前台处理后传来的文件名称private String uploadFileName;public String upload() throws Exception {// TODO Auto-generated method stub//获取项目部署根目录String path=ServletActionContext.getServletContext().getRealPath("")+"\\upload";//用时间戳来作为保存后的文件名称String newFileName=new SimpleDateFormat("yyyyMMddHHmmssSS").format(new Date());//获取文件的后缀String suffix=uploadFileName.substring(uploadFileName.lastIndexOf("."));//名称加后缀形成完整的文件名newFileName+=suffix;//创建一个文件输入流FileInputStream fileInput=new FileInputStream(upload);//创建一个文件输出流FileOutputStream fileOutput=new FileOutputStream(new File(path+"\\"+newFileName));//声明一个缓冲来存读取的字节byte[] b=new byte[1024];//文件的长度int length;//如果不返回-1就继续读取并写入另一个文件中while((length=fileInput.read(b))!=-1){fileOutput.write(b,0,length);}//关闭流fileOutput.close();fileInput.close();return "success";}


原创粉丝点击