Struts2 文件上传与下载 常见问题

传统的HTML里上传文件如下所示:

<form method="pose" action="xxx" enctype="multipart/form-data">
      <input type="file" size="40">
</form>

表单enctype的默认属性是application/x-www-form/urlencoded,这种方案使用有限的字符集,当使用非字母和数字的字符时,将被%HH代替,因此一个中文字符会被描述为%HH%HH,这样上传的数据量将是原始数据量的2-3倍,所以后来改用了一种新型的媒体类型multipart/form-data

在实际的应用中,发现经常出现各种问题:

1:抱xxx工程/xx目录 拒绝访问

   因为我用的是 jsmartcom 的jar包上传的。也就是smart upload的上传组件,通过servlet实现。而我用的是struts2的上传功能。追根溯底发现是smart upload 的请求被struts2给拦截了,造成找不到存放临时文件的目录。由此可以看出smart upload的上传机制应该和struts2的一致。

        找到原因就好办了,解决方法就是不让struts拦截servlet的请求。看一下web.xml的配置,原来拦截的是 /* 所有的请求。好办,把 /* 改为  *.action 就OK了,测试通过

2:经常出现什么action找不到

   解决方法:1:检查你写的struts.xml文件是不是拼写错误,更不能有大小写错误,笔者经常出现Struts.xml错误

                2:检查web.xml是否指定了struts的拦截器

                3:页面标签错误

3:Unable to find 'struts.multipart.saveDir' property setting.

   解决办法:在struts.xml里配置<constant name="struts.multipart.saveDirg" value="**"/>

                 或者在struts.properties里添加struts.multipart.saveDir="d:\\uploadFile"

4:文件太大,比如经常报超过了2097152

   解决办法:在struts.properties里增加一条struts.multipart.maxSize=***

文件下载:在struts2中下载文件已经被集成到框架中,用一个stream流来表达(具体结果类型就是streamResult)

详细例子如下:

1:在页面端

<s:url id="url" action="download"></s:url>
<s:a href="%{url}">下载file组件</s:a>

2:在struts.xml端

  

<!-- begin:实现文件下载 -->
<action name="download" class="**">
   <param name="inputPath">
       /WEB-INF/uploadFiles/file-down.zip
   </param>
   <result name="input">
      /WEB-INF/pages/download.jsp
   </result>
   <result name="success" type="stream">
        <param name="contentType">
              application/zip</param> 
        <param name="inputName">inputStream</param>
        <param name="contentDisposition">
                  filename="file-down.zip"
        </param>
        <param name="bufferSize">2048</param>
   </result>
</action>
<!-- end:实现文件下载 -->

 这里简单介绍下这几个参数,第一个inputPath表示输入流的路径,要求是到文件

        第二个参数contentType表示文件下载类型(MIME类型)

        第三个参数inputName是action里调用的方法名

        第四个参数默认是inline字符串,但不可不写。实际上这里指的是具体文件名

3:在Action端

   

private String inputPath;
	
	@Override
	public String execute() throws Exception {		
		return SUCCESS;
	}
	
	public String input() throws Exception{
		return INPUT;
	}

	public InputStream getInputStream() throws IOException{
		InputStream is= ServletActionContext.getServletContext().
    getResourceAsStream(inputPath);
		return is;		
	}
	
	public String getInputPath() {
		return inputPath;
	}

	public void setInputPath(String inputPath) {
		this.inputPath = inputPath;
	}

                   这里inputPath是从struts.xml文件获取的,但是具体的结果展示是依靠streamResult类来完成的

  

猜你喜欢

转载自bestchenwu.iteye.com/blog/1025789
今日推荐