Struts2文件上传大小限制

Struts2中struts.multipart.maxSize指定允许上传的文件的最大字节数。默认值是2097152,2M。

<constant name="struts.multipart.maxSize" value="104857600" />

将允许上传文件的长度修改成100M。

如果上传的文件长度大于struts.multipart.maxSize属性的值,那么底层的commons-fileupload组件将抛出org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException,直接把该异常的消息设置为Action级别的错误消息。如果你在页面中使用

<s:actionerror/>标签,将看到如下的错误:
the request was rejected because its size (128631583) exceeds the configured maximum (104857600)
对异常进行处理,重写ActionSupport类的addActionError方法
public void addActionError(String anErrorMessage){
		
		//这里要先判断一下,是我们要替换的错误,才处理
		if (anErrorMessage.startsWith("Request exceeded allowed size limit")) { 
			
			uploadResult = "上传文件超过限制长度10M";
			
			//将信息替换
			super.addActionError("上传文件超过限制长度100M");
		}else{
			super.addActionError(anErrorMessage); 
		}
	}
调用addActionError方法后会去寻找result为input的映射,定义result为input的映射。
<result name="input" type="json">
            	<param name="includeProperties">uploadResult</param>
            	<param name="contentType">text/html</param>
        	</result>
 

如果  业务允许上传文件大小(如10M) < 上传的文件大小 < struts.multipart.maxSize属性的值(如100M),编写业务方法提示错误信息。

public String uploadAttachment() throws Exception {

		// 判断是否选择文件
		if (file == null || fileFileName == null || fileContentType == null) {
			uploadResult = "未选择文件";
			return "uploadAttachment";
		}

		// 限制上传文件大小10M以内
		if (file.length() > 10485760) {
			uploadResult = "上传文件超过限制长度10M";
			return "uploadAttachment";
		}

		String newFileName = null;

		// 得到保存上传文件的目录的真实路径
		String path = ServletActionContext.getServletContext().getRealPath(
				uploadDir);

		File dir = new File(path);

		// 如果这个目录不存在,则创建它
		if (!dir.exists())
			dir.mkdir();

		int index = fileFileName.lastIndexOf('.');

		// 采用UUID的方式随机命名

		if (index != -1)
			newFileName = UUID.randomUUID().toString()
					+ fileFileName.substring(index);
		else
			newFileName = UUID.randomUUID().toString();

		try {

			BufferedOutputStream bos = null;
			BufferedInputStream bis = null;

			FileInputStream fis = new FileInputStream(file);
			bis = new BufferedInputStream(fis);

			FileOutputStream fos = new FileOutputStream(new File(dir,
					newFileName));
			bos = new BufferedOutputStream(fos);

			byte[] buf = new byte[4096];

			int len = -1;
			while ((len = bis.read(buf)) != -1) {
				bos.write(buf, 0, len);
			}

			if (null != bis)
				bis.close();

			if (null != bos)
				bos.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

		fileVo = new FileVo(fileFileName, newFileName);

		uploadResult = "成功";
		
		return "uploadAttachment";
	}

完整的struts.xml

 <result name="uploadAttachment" type="json">
            	<param name="includeProperties">uploadResult,fileVo.*</param>
            	<param name="contentType">text/html</param>
        	</result>
        	
        	<result name="input" type="json">
            	<param name="includeProperties">uploadResult</param>
            	<param name="contentType">text/html</param>
        	</result>

applyProjectStepOne.jsp

function processUploadJson(data){
				
				var file = $("#file");
				file.after(file.clone().val("")); 
				file.remove(); 
				
        		if(data.uploadResult=='成功'){
        			
        			var $span=$("<span id='"+data.fileVo.savedName.substring(0,data.fileVo.savedName.indexOf("."))+"'></span>");
			  		$span.append(data.fileVo.realName);			  				
			  		$span.append("<input type='hidden' name='realName' value='"+data.fileVo.realName+"'>");
			  		$span.append("<input type='hidden' name='savedName' value='"+data.fileVo.savedName+"'>");			  				
			  		$span.append("     ");			  				
			  		$span.append("<a href='javascript:deleteAttachment(\""+data.fileVo.savedName.substring(0,data.fileVo.savedName.indexOf("."))+"\");'>删除</a>");			  				
			  		$span.append("<br/>");			  				
			  		$("#attachments").append($span);
			  		
        		}else{
        			alert(data.uploadResult);
        		}
    		}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值