Struts2批量上传文件

需用到两个包

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="file" name="upload"/>
    	<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 {
			
			FileInputStream fileInput=null;
			FileOutputStream fileOutput=null;
			String path=ServletActionContext.getServletContext().getRealPath("")+"\\upload";
			
			for(int i=0;i<upload.length;i++){
				//用时间戳来作为保存后的文件名称
				String newFileName=new SimpleDateFormat("yyyyMMddHHmmssSS").format(new Date());
				//获取文件的后缀
				String suffix=uploadFileName[i].substring(uploadFileName[i].lastIndexOf("."));
				//名称加后缀形成完整的文件名
				newFileName+=suffix;
				
				fileOutput=new FileOutputStream(new File(path+"\\"+newFileName));
				fileInput=new FileInputStream(upload[i]);
				
				byte[] b=new byte[1024];
				int length;
				
				while((length=fileInput.read(b))!=-1){
					fileOutput.write(b,0,length);
				}
			}
			fileOutput.close();
			fileInput.close();
			return "success";
		}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值