文件上传 Struts2 fileupload

struts2文件上传下载非常的简单。

 

给我们提供了非常简洁的方式来上传文件。

 

其中我们需要用到的jar文件主要是:commons-io-1.3.2.jar 和 commons-fileupload-1.2.1.jar

 

然后需要注意的是,我们在写表单的时候,就是必须在写页面表单的时候 需要 将form表单的

enctype="multipart/form-data"

 

前台

 

 

<form enctype="multipart/form-data"
		action="${pageContext.request.contextPath}/test/file/upload.action" method="post">
		<input type="file" name="uploadImage">
		<input type="submit" value="upload">
</form>

 

 

struts2配置文件

 

 

<package name="file" namespace="/test/file" extends="struts-default">
		<action name="*" class="com.anduo.action.FileUploadAction" method="{1}">
			<result name="success">/success.jsp</result>
                </action>
</package>

 

 

后台Action 代码

 

 

package com.anduo.action;

import java.io.File;

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

import com.opensymphony.xwork2.ActionContext;

public class FileUploadAction {
	private File uploadImage;// 得到上传的文件 特别注意的是在这里的文件名必须跟前台的input 标签中的name 一致
	private String uploadImageContentType;// 得到文件的类型
	private String uploadImageFileName;// 得到文件的名称

	

	// 这里略省了属性的getter/setter方法


	public String upload() throws Exception {
		// 获得项目路径
		String realpath = ServletActionContext.getServletContext().getRealPath(
				"/images");
		if (uploadImage != null) {
			File file = new File(realpath);
			if (!file.exists()) {
				file.mkdirs();
			}
			FileUtils.copyFile(uploadImage, new File(file, uploadImageFileName));
			ActionContext.getContext().put("message",
					"文件上传成功!" + realpath + "/" + uploadImageFileName);
		}
		return "success";
	}
}

 

success.jsp

 

${message}
 

请看效果

 




 

 



上文文件成功了吧。

 

如果我们没有指定上传文件的存放路径,struts2会在action结束后移除临时文件

 

也就是我们根本就找不到我们上传的东西了。吼吼~~~

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值