开发日志:struts2使用commons.fileupload上传附件,并解决upload.parseRequest(request)为空的问题

本文介绍了如何在Struts2框架中使用commons-fileupload组件处理multipart/form-data表单,实现文件上传功能。通过创建自定义请求解析器和配置Struts2,成功解决了上传过程中遇到的问题,并提供了详细的代码实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

要做一个phongap开发的App上传文件到服务器的Action,打算使用commons.fileupload的方式

接口jsp页面

<form  action="uploadAction.action" method="post" enctype="multipart/form-data">
			<table>
				<tr><td>上传附件:uploadAction.action</td></tr>
				<tr><td><input name="file" type="file" size="20" ></td><td>上传图片</td></tr>
				<tr><td colspan="2" align="center"><input type="submit" value="上传"/></td></tr>
			</table>
		</form>


保存附件的Action方法

/**
	 * 初始化目录(如果目录不存在,新建)
	 * @param uploadPath 保存路径
	 * @param tempPath 临时文件路径
	 * @throws ServletException
	 */
	private void initDir(String uploadPath,String tempPath) throws ServletException{
		File uploadFile = new File(uploadPath);
		if (!uploadFile.exists()) {
			uploadFile.mkdirs();
		}
		File tempPathFile = new File(tempPath);
		if (!tempPathFile.exists()) {
			tempPathFile.mkdirs();
		}
	}
	
	public String uploadAction()throws Exception{
		try {
			Date date = new Date();
			//上传文件
			request.setCharacterEncoding("UTF-8");
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
			String basePath = ServletActionContext.getRequest().getRealPath("/");//获取根目录
			//设置下载目录
			String uploadPath = basePath + "/upload";
			//设置临时目录
			String tempPath = uploadPath +"/temp";
			//uploadPath = uploadPath +"/"+ date.getTime();//添加时间目录防止重复
			this.initDir(uploadPath, tempPath);
			File tempPathFile = new File(tempPath);
	        factory.setRepository(tempPathFile);// 设置缓冲区目录
			ServletFileUpload upload = new ServletFileUpload(factory);
			//upload.setSizeMax(34194304); 设置最大文件尺寸,4MB
			List items = upload.parseRequest(request);//得到所有的文件
			Iterator itr = items.iterator();
			
			
			while(itr.hasNext()){
				FileItem fileItem = (FileItem) itr.next();
				if(fileItem.isFormField()){
					System.out.println("表单参数名:"+fileItem.getFieldName()+",表单参数值:"+fileItem.getString("utf-8"));
				}else{
					if(fileItem.getName()!=null && !"".equals(fileItem.getName())){
						System.out.println("上传文件的大小:"+fileItem.getSize());
						System.out.println("上传文件的类型:"+fileItem.getContentType());
						System.out.println("上传文件的名称:"+fileItem.getName());
						//保存文件
						File saveFile = new File(uploadPath,fileItem.getName());
						fileItem.write(saveFile);
						imgUrl = uploadPath+"/"+fileItem.getName();
						System.out.println("上传成功");
					}else{
						System.out.println("没有上传文件");
					}
				}
				
			}
			
			
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
	}

调用Action的时候发现
List items = upload.parseRequest(request);

items的值一直为空,网上找了下原因:参考http://blog.youkuaiyun.com/qq964166471/article/details/21385041

原因是struts2把原始的原来S2为简化上传功能,把所有的enctype="multipart/form-data"表单做了wrapper最后把HttpServletResquest封装成 org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper


我采用的解决步骤

1、新建MyRequestParser类,重写parse方法,里面内容为空

public class MyMultiPartRequest extends JakartaMultiPartRequest{

	@Override
	public void parse(HttpServletRequest servletRequest, String arg1) throws IOException {
		
	}
	
}

2、设置完后,使用上面方法的上传成功了,但原本使用struts2方式上传失败了- -!对此,我做了下面的处理

@Override
	public void parse(HttpServletRequest request, String arg1) throws IOException {
        String url = request.getRequestURI().toString();//取得请求的URL
        if(url.indexOf("uploadWebApp.action")>0){//调用的是uploadWebApp.action方法
        	//不需要struts2的处理
        }else{
        	//需要struts2的处理,调用回父类的方法
        	super.parse(request, arg1);
        }
	}



3、最后在struts下增加下面内容

<struts>
	
	<bean type="org.apache.struts2.dispatcher.multipart.MultiPartRequest" 
		  name="myMultiPartRequest" class="com.MyMultiPartRequest" 
		  scope="default" optional="true"/>
	<constant name="struts.multipart.handler" value="myMultiPartRequest" />  


重启tomcat后上传成功

如果不想修改配置,可以使用servlet, 参考http://blog.chinaunix.net/uid-21162795-id-3247663.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值