zoukankan      html  css  js  c++  java
  • struts2文件上传

    1、实现struts2的文件上传,首先把表单form的enctype属性设置为:multipart/form-data

    <form action="FileUpload" method="post" enctype="multipart/form-data">
    			文件标题:<input name="title" type="text" /><br>
    			文件:<input name="upload" type="file"/><br>
    			<input type="submit" value="上传" />
    		</form>

    2、然后加入FileUploadAction,当中有几个属性:upload、uploadFileName、uploadContentType、savePath,当中upload属性为File类型,action类直接通过File类型属性来封装上传的文件内容,struts2直接把上传的文件名称以及文件类型的信息封装在xxxFileName和xxxContentType中,而savePath则是通过struts.xml配置文件里配置的路径

    action类为:

    public class FileUploadAction {
    	private String title;
    	private File upload;
    	private String uploadFileName;
    	private String uploadContentType;
    	private String savePath;             (getter/setter)
    public String execute() throws Exception {
    		System.out.println("path:" + getSavePath());
    		System.out.println("filename:" + getUploadFileName());
    		String path = ServletActionContext.getServletContext().getRealPath(getSavePath());// 相对路径
    		try {
    			FileOutputStream fos = new FileOutputStream(path + "\" + getUploadFileName());
    			byte[] buffer = new byte[1024];
    			int len;
    			FileInputStream fis = new FileInputStream(getUpload());
    			while ((len = fis.read(buffer)) > 0) {
    				fos.write(buffer, 0, len);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return "success";
    	}
    }
    这里要注意的是,假设struts配置文件里savePath配置的是相对路径的话,则须要通过
    String path = ServletActionContext.getServletContext().getRealPath(getSavePath());
    来获取相对路径。假设是绝对路径的话。可直接使用
    FileOutputStream fos = new FileOutputStream(<span style="font-family: Arial, Helvetica, sans-serif;">getSavePath()</span> + "\" + getUploadFileName());

    3、加入上传成功后转向的页面

    上传成功!
    		<br>
    		文件标题:
    		<s:property value="title" />
    		<br />
    		文件为:
    		<img src="<s:property value="'upload/'+uploadFileName"/>" />
    		<br />

    这里以显示图片为例


    4、最后是配置action

    <action name="FileUpload" class="com.demo.action.FileUploadAction">
    			<!-- 动态设置action属性值 -->
    		    <param name="savePath">/upload</param>
    			<result name="success">/demo/jsp/uploadSuccess.jsp</result>
    		</action>
    这里配置的是相对路径。须要在项目WebRoot下建立upload目录


    5、最后在web.xml里配置一个Filter,ActionContextCleanUp。作用是方便struts2和SiteMesh整合,事实上本来和文件上传没有什么关系,但发现有时候会出现一些未知的异常,但加了这个Filter后就一切正常了

    <filter>
    		<filter-name>struts-cleanup</filter-name>
    		<filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
    	</filter>
    <filter-mapping>
    		<filter-name>struts-cleanup</filter-name>
    		<url-pattern>/*</url-pattern>
    	</filter-mapping>

    但启动是后台出现了错误

    ***************************************************************************
    *                                 WARNING!!!                              *
    *                                                                         *
    * >>> ActionContextCleanUp <<< is deprecated! Please use the new filters! *
    *                                                                         *
    *             This can be a source of unpredictable problems!             *
    *                                                                         *
    *                Please refer to the docs for more details!               *
    *              http://struts.apache.org/2.x/docs/webxml.html              *
    *                                                                         *
    *************************************************************************

    因为在struts升级时这个配置有漏洞,所以用下面配置取代

    <filter>
    		<filter-name>struts-prepare</filter-name>
             <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter</filter-class>
    	</filter>
    	<filter-mapping>
             <filter-name>struts-prepare</filter-name>
             <url-pattern>/*</url-pattern>
         </filter-mapping>
         
         <filter>
             <filter-name>struts-execute</filter-name>
             <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter</filter-class>
         </filter>
         <filter-mapping>
             <filter-name>struts-execute</filter-name>
             <url-pattern>/*</url-pattern>
         </filter-mapping>




    这里遇到一个问题。当上传的文件名称为中文时,会出现乱码的情况。仅仅须要在struts.xml中配置

    <!-- 设置应用使用的解码集 -->
    	<constant name="struts.i18n.encoding" value="UTF-8"/>

    接着,又出现上传文件出错了,原来是struts2对上传的文件大小默认作了限制为2M。我们能够通过配置struts.xml来改动大小

    <!-- 改动默认文件上传大小 -->
    	<constant name="struts.multipart.maxSize" value="52428800"/>

    value处仅仅能为计算的终于值。不能写成value="1024*1024*50"

    有时。我们要限制上传的文件类型。能够配置fileUpload的拦截器

    在struts的action配置里加入拦截器,配置同意上传的类型,这里一定要配置默认的拦截器。同一时候配置input的result,当出错时返回原页面并提示错误

    <interceptor-ref name="fileUpload">
    				<param name="allowedTypes">image/jpeg,image/gif,image/png,application/pdf</param>
    				<param name="maximumSize">52428800</param>
    			</interceptor-ref>
    			<interceptor-ref name="defaultStack"></interceptor-ref>
    我们须要多加入个国际化信息文件message_zh_CN.properties。用以配置错误信息

    struts.messages.error.content.type.not.allowed=the content type of file is not allowed
    struts.messages.error.file.too.large=file too large
    struts.messages.error.uploading=some false is unknown
    并在struts配置文件里加入

    <!-- 加入国际化信息 -->
        <constant name="struts.custom.i18n.resources" value="message"/>



    多文件上传

    多文件上传事实上也非常easy,action中原来的属性改为数组类型或者List类型,这里改为List类型

    public class MultiUploadAction extends ExampleSupport {
    	private String title;
    	private List<File> upload;
    	private List<String> uploadFileName;
    	private List<String> uploadContentType;
    	private String savePath;
            (getter/setter)
            public String execute() {
    		List<File> fileList = getUpload();
    		String path = ServletActionContext.getServletContext().getRealPath(getSavePath());
    		try {
    			for (int i = 0; i < fileList.size(); i++) {
    				FileOutputStream fos = new FileOutputStream(path + "\" + getUploadFileName().get(i));
    				byte[] buffer = new byte[1024];
    				int len;
    				FileInputStream fis = new FileInputStream(getUpload().get(i));
    				while ((len = fis.read(buffer)) > 0) {
    					fos.write(buffer, 0, len);
    				}
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    			return INPUT;
    		}
    		return SUCCESS;
    	}
    }
    同一时候页面也加入多几个file类型的input就可以

    <s:form action="MultiUpload" method="post" enctype="multipart/form-data">
        	文件描写叙述:<input name="title" type="text"/><br/>
        	第一个文件:<input name="upload" type="file"/><br/>
        	第二个文件:<input name="upload" type="file"/><br/>
        	第三个文件:<input name="upload" type="file"/><br/>
        	<s:submit value="上传"/>
        </s:form>





  • 相关阅读:
    富文本编辑器Ueditor
    记一个好用的轮播图的FlexSlider
    记一次couchbase(memcached)安装以及使用
    写了一个联动select的jquery选择器
    ios访问手机通讯录获取联系人手机号
    Swift中自定义SubString
    Swift中给UIView添加Badge
    Swift计算两个经纬度之间的球面面积
    Swift项目使用SWTableViewCell
    SQLite.Swift 中的一些用法
  • 原文地址:https://www.cnblogs.com/wgwyanfs/p/7234268.html
Copyright © 2011-2022 走看看