struts2文件上传

struts2文件上传实例:
1.upload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>文件上传</title>
  </head>
  <body>
    <s:form action="upload" method="post" enctype="multipart/form-data">
	<s:file name="file"></s:file>
	<s:submit value="submit"></s:submit>
</s:form>
  </body>
</html>

2.uploadSuccess.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>文件下载成功页面</title>
  </head>
  <body>
    	file upload Success!
  </body>
</html>

3.UploadAction.java
package com.hitsoft.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
	private File file;//对应真正上传的文件
	private String fileFileName;//对应上传的文件名
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	public String getFileFileName() {
		return fileFileName;
	}
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	public String execute() throws Exception{
		InputStream is = new FileInputStream(file);
		OutputStream os = new FileOutputStream("c:\\" +fileFileName);
		byte[] buffer = new byte[1024];
		int length = 0;
		while((length=is.read(buffer))!=-1){
			os.write(buffer, 0, length);
		}
		os.close();
		is.close();
		return SUCCESS;
	}
}


4.struts.xml
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="struts2"  extends="struts-default">
	<!-- 文件上传:需要commons-io.2.0.1.jar-->
	<action name="upload" class="com.hitsoft.action.UploadAction">
		<result name="success">/uploadSuccess.jsp</result>
	</action>
    </package>
</struts>


5.lib目录中的jar包:
commons-fileupload-1.2.1.jar
commons-logging.jar
freemarker-2.3.15.jar
ognl-2.7.3.jar
struts2-core-2.1.8.1.jar
xwork-core-2.1.6.jar
commons-io.2.0.1.jar
6.访问地址:
http://localhost:8080/struts2/upload.jsp
选择本机文件,点击上传,然后去本机C盘下查看文件是否下载成功。

你可能感兴趣的:(struts2)