Struts2.x+FileUpload实现单文件上传

选择所要上传的文件css

upload.jsphtml

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>   <%//引入struts2标签  %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  <table align="center" width="50%">
   <tr>
    <td>
   <% // <s:fielderror cssStyle="color:red"/>%>
    </td>
   </tr>
  </table>
  
  <s:form action="upload" theme="simple" enctype="multipart/form-data"> <%//设置form表单的enctype属性为multipart/form-data  %>
    <table align="center" width="50%" border="1">
      <tr>
	    <td>file</td>
	    <td><s:file name="file"></s:file>
	  </tr>			
	  <tr>
	    <td><s:submit value="submit"></s:submit></td>
	    <td><s:reset value="reset"></s:reset></td>
	  </tr>			
    </table>
  </s:form>
</body>
</html>

实现文件上传功能java

UploadAction.javaapache

 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;


import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport{
private File file;      //建立file属性
private String fileFileName;   //建立fileFileName属性,表明文件名称
private String fileContentType;  //建立fileContentType属性,表明文件类型
 
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 getFileContentType() {
		return fileContentType;
	}

public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

public String execute() throws Exception
{
	
		InputStream is = new FileInputStream(file);

		String root = "E:/shang";  //设置上传的路径

		File destFile = new File(root, this.getFileFileName()); //destFile文件:输出流的目的文件

		OutputStream os = new FileOutputStream(destFile);       //os文件:关于destFile文件的输出流

		byte[] buffer = new byte[400];  //buffer字节数组:实现输入流与输出流的转换

		int length = 0;

		while ((length = is.read(buffer)) > 0)
		{
			os.write(buffer, 0, length);
		}

		is.close();

		os.close();
	

	return SUCCESS;

  }
}

 配置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="myPackage" extends="struts-default">
    	<!-- 访问首页 -->
        <action name="upload" class="com.lyq.upload.UploadAction">
            <result>uploadResult.jsp</result>
        </action>
        </package>
    </struts>
相关文章
相关标签/搜索