这篇博客同时也在我的个人网站上有,由于想让更多人看到,所以也在这里发一下
我的个人网站:www.wenjingyi.top
下载
直接上步骤
- 在Action类中准备文件名
- 在Action类中准备文件流
- 配置struts.xml文件
文件名
最好在Action类中给出,再让struts.xml文件得到这个文件名。文件流
既然是下载,那么文件流就必不可少。将Action写成以下模样
配置struts.xml
添加以下Action配置完,启动tomcat,在浏览器中输入,http://localhost:8080/xxx/download?fileName=hosts,访问则会提示下载。这个下载要求服务器中xxx项目中存在/WEB-INF/file/hosts文件
往result稍稍深入了解。下载的处理result是stream,在 struts-default.xml配置文件中可以找到对应的类为
:org.apache.struts2.result.StreamResult
打开对应源码,会看见这些属性。 这些就是在配置struts.xml的时候可以覆盖的属性。当然并不是所有属性都需要覆盖。在这个类的类文档中给出了一个例子。
* <result name="success" type="stream"> * <param name="contentType">image/jpeg</param> * <param name="inputName">imageStream</param> * <param name="contentDisposition">attachment;filename="document.pdf"</param> * <param name="bufferSize">1024</param> * </result>
上传
- Action类中要有File类型的属性,及其setter
- jsp页面表单
- 可选地,在struts.xml中配置constant,以改变上传的限制大小
Action类
表单
表单中有几点需要注意- method需要为POST
- enctype需要为multipart/form-data
- 对应文件input的name属性要和Action类中的File对象名对应