struts中的文件上传

struts中的文件上传

1、上传页面代码

<body>
    <form action="file" enctype="multipart/form-data" method="post">
    	图片上传}:<input type="file" name="image">
    	<br/>
    	<input type="submit" value="提交">
    </form>
</body>

2、struts.xml里面action配置

<action name="file" class="com.edu.hpu.action.FileAction">
        <result>/fileuploadsuccess.jsp</result>
</action>

 

 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 {
	private File image;
	
	/**
	 * 使用规范:
	 * imageFileName:image(前面文件的名字) + FileName(固定写法)
	 */
	private String imageFileName;

	@Override
	public String execute() throws Exception {
		//获得文件存储路径
		String path = ServletActionContext.getServletContext().getRealPath("/images");
		
		//创建相应文件对象
		File saveFile = new File(new File(path),imageFileName);
		System.out.println(saveFile);

		//创建文件存路径
		if(!saveFile.getParentFile().exists()) {
			saveFile.getParentFile().mkdirs();
		}
		
		//保存文件
		FileUtils.copyFile(image, saveFile);
		return super.execute();
	}
	
	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;
	}

}

 4、结果展示页面

 

 

<body>
  文件<s:property value="imageFileName"/>,上传成功!
</body>

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值