struts多文件上传

struts多文件上传

1、文件载入页面

 

  <body>
    <form method="post" enctype="multipart/form-data" action="file_load">
    	文件一:<input type="file" name="images"><br/>
    	文件二:<input type="file" name="images"><br/>
    	文件三:<input type="file" name="images"><br/>
    	<input type="submit" value="提交"/>
  </form>
</body>

 2、struts.xml里面action配置

 

 

<struts>
	<package name="default" namespace="/" extends="struts-default" >
		<action name="file_*" class="com.edu.hpu.action.FileAction" method="{1}">
			<result>/file_{1}.jsp</result>
		</action>
	</package>
</struts>

 3、FileAction

 

 

package com.edu.hpu.action;

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class FileAction extends ActionSupport {
	/**
	 * 使用数组进行多文件接收
	 * images:接收到的文件
	 * imagesFileName:接收到的文件名
	 */
	private File[] images;
	private String[] imagesFileName;

	public File[] getImages() {
		return images;
	}

	public void setImages(File[] images) {
		this.images = images;
	}

	public String[] getImagesFileName() {
		return imagesFileName;
	}

	public void setImagesFileName(String[] imagesFileName) {
		this.imagesFileName = imagesFileName;
	}

	@Override
	public String execute() throws Exception {
		return super.execute();
	}
	
	public String input() throws Exception {
		return SUCCESS;
	}
	
	public String load() throws Exception  {
		//获得并创建存储路径
		String savePath = ServletActionContext.getServletContext().getRealPath("/images");
		File filePath = new File(savePath);
		if(!filePath.exists()) {
			filePath.mkdirs();
		}
		
		//遍历获得文件进行文件存储
		for(int i = 0; i < images.length; i++) {
			File file = new File(filePath,imagesFileName[i]);
			if(!file.exists()) {
				file.createNewFile();
			}
			System.out.println(file.getAbsolutePath());
			FileUtils.copyFile(images[i], file);
		}
		return SUCCESS;
	}
}

 4、结果展示页面

<body>
  文件
  <s:iterator value="imagesFileName" var="fileName">
 	<s:property value="fileName"/>,
 </s:iterator>上传成功!
</body>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值