struts2文件上传

由于当时写Demo时,是在原来的HelloWorld 上改,所以类名没有改过来。

Action类的代码主如下

/**
 * 
 */
package com.demo.view.action;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

/**
 * @author Administrator
 *
 */
public class HelloWorld {
	
	private File image;
	private String imageFileName;
	private String imageContentType;
	

	public File getImage() {
		return image;
	}


	public void setImage(File image) {
		this.image = image;
	}


	public String getImageFileName() {
		return imageFileName;
	}


	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}


	public String getImageContentType() {
		return imageContentType;
	}


	public void setImageContentType(String imageContentType) {
		this.imageContentType = imageContentType;
	}
	
	public String getHello(){
		return "success";
	}


	public String upload() throws IOException{
		String realPath=ServletActionContext.getServletContext().getRealPath("/images");
		System.out.println(realPath);
		if(null!=image){
			File saveFile=new File(new File(realPath),imageFileName);
			if(!saveFile.getParentFile().exists()){
				saveFile.getParentFile().mkdirs();
			}
			FileUtils.copyFile(image,saveFile);
			ServletActionContext.getRequest().setAttribute("message", "文件上传成功");
			
		}
		
		return "success";
	}

}

  

 

   struts.xml配置文件

 

<struts>
	<package name="myDemo"  namespace="/demo"  extends="struts-default">
		<action name="helloWorld_*" class="com.demo.view.action.HelloWorld" method="{1}">
			<result name="success">
				/WEB-INF/pages/hello.jsp
			</result>
		</action>
	</package>
</struts>

 

  jsp页面

 

  <body>
   <form action="helloWorld_upload" method="post" enctype="multipart/form-data">
   	文件:<input type="file" name="image"><br>
   	<input type="submit" value="上传">
   </form>
   ${message }
  </body>

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值