(9)Struts2文件上传

 

Struts2文件上依赖jar包:commons-io-1.3.2.jar、commons-fileupload-1.2.1.jar

1、首先在实体类,如User中中设置三个属性分别为:xxx、xxxContextType、xxxFileName.并提供相关的getter和sers方法。

//文件上传相关属性
	private File upload;
	private String uploadContentType;
	private String uploadFileName;


2、在Action中提供下载方法,如名为fileupload方法:

public String fileupload() throws Exception {
		//处理上传
		if(user.getUpload() != null) {
			String path = ServletActionContext.getServletContext().getRealPath("/upload");
			File destFile = new File(path, user.getUploadFileName());
			FileUtils.copyFile(user.getUpload(), destFile);
			user.getUpload().delete();
			user.setPath(path);
			user.setFileName(user.getUploadFileName());
		}
		
		userService.save(user);
		
		return "toList";
	}


3、在struts.xml文件中配置对上传文件的属性限制,如上文文件的大小、扩展名等

		<interceptor-ref name="defaultStack">
			<param name="fileUpload.maximumSize">20971520</param>
              		<!-- 配置上传文件允许的类型,如果配置多个值的话,用","隔开 -->
              		<param name="fileUpload.allowedTypes">text/plain,application/msword</param>
              		<!-- 配置上传文件的扩展名,如果配置多个值的话,用","隔开 -->
              		<param name="fileUpload.allowedExtensions">.txt</param>
		</interceptor-ref>


 


 

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值