Struts2 文件上传

1 设计文件上传表单

注意:表单必须把enctype改为"multipart/form-data"

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>一点教程-struts2的文件上传</title>
  </head>
  <body>
  <h3>文件上传</h3>
  <form action="demo1.action" method="post" enctype="multipart/form-data">
  	用户名:<input type="text" name="name"/><br/>
  	密码:<input type="password" name="password"/><br/>
  	请选择头像:<input type="file" name="icon"/><br/>
  	 <input type="submit" value="修改"/>
  </form>
  </body>
</html>

2 编写Action接收文件

注意:表单的name必须和Action的属性名保持一致

package com.yiidian.action;
import java.io.File;

import com.opensymphony.xwork2.ActionSupport;
/**
 * 接收文件和参数
 * @author 一点教程(yiidian.com)
 */
public class Demo1Action extends ActionSupport{
	//接收表单普通参数
	private String name;
	private String password;
	public void setName(String name) {
		this.name = name;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	//接收文件信息
	private File icon; //内容
	private String iconFileName;//名称
	private String iconContentType;//类型
	public void setIcon(File icon) {
		this.icon = icon;
	}
	public void setIconFileName(String iconFileName) {
		this.iconFileName = iconFileName;
	}
	public void setIconContentType(String iconContentType) {
		this.iconContentType = iconContentType;
	}
	
	@Override
	public String execute() throws Exception {	
		System.out.println("name="+name);
		System.out.println("password="+password);
		System.out.println("文件内容--"+icon);
		System.out.println("文件名称--"+iconFileName);
		System.out.println("文件类型--"+iconContentType);	
		return SUCCESS;
	}
}

3 struts.xml配置Action

注意:这里可以修改文件上传大小的常量

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
	"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
	<!-- 修改文件上传大小常量,默认为2M -->
	<constant name="struts.multipart.maxSize" value="20971520"></constant>

	<package name="base" extends="struts-default" namespace="/">
		<action name="demo1" class="com.yiidian.action.Demo1Action">
			<result>/succ.jsp</result>
		</action>
	</package>	
</struts>

4 运行测试

控制台输出

 

源码下载:https://pan.baidu.com/s/1OmKEVBlss0nHlvqCpnSsvA

热门文章

优秀文章