Struts2 文件上传

更详细的介绍参见:
http://www.blogjava.net/max/archive/2007/03/21/105124.html
所要用到的jar
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
commons-logging-1.0.4.jar
commons-logging-1.1.1.jar
freemarker-2.3.13.jar
ognl-2.6.11.jar
struts2-core-2.1.6.jar
xwork-2.1.2.jar  

如果是直接用SSH中的Strutsjar包 记得删除Struts2-Spring-Plugin

否则系统会认为你spring的部分没有配置上   对于仅使用struts的项目而言 这个包不是多余 而是不能有

Eclipse JEE编辑器不是那么的智能  创建web工程没有加入Servlet的jar包  需要自己手动添加

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">


    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

struts配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
    <constant name="struts.devMode" value="true"></constant>
    <constant name="struts.action.extension" value="do,action"></constant>

    <package name="struts2" extends="struts-default" namespace="/">
        <action name="UploadAction_*" class="action.UploadAction"
            method="{1}">
            <result name="success">/upload.jsp</result>

        </action>
    </package>
</struts>   


页面

<%@page contentType="text/html; charset=GBK" language="java"%>
<%@taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Struts 2 File Upload</title>
    </head>
    <body>
        <s:form action="UploadAction_uploadEssays.action" method="POST"
            enctype="multipart/form-data">
            <s:file name ="myFile" />
            <s:file name ="myFile" />
            <s:file name ="myFile" />
            <s:textfield name="caption" label="Caption" />
            <s:submit />
        </s:form>
    </body>
</html>

UploadAction

package action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {
    private static final long serialVersionUID = 572146812454l;
    private static final int BUFFER_SIZE = 16 * 1024; // 这里的BUFFER_SIZE
                                                        // 表示一个数据缓冲区是16KB
    // 所以写出的文件最小是16KB

    private File[] myFile; //myFile就是用户准备上传的文件
    private String[] myFileContentType;
    private String[] myFileFileName; //用户上传文件的真实文件名
    //当然了 这里的属性命名是任意的
    //但是要保证和页面元素中的 name属性的值要匹配
    //比如 页面中input 的name是myFile 我这里就应该有 setMyFile  getMyFile
    //为了减少出错, 属性都用对应的名字好了
    //若文件对象的名字是xxx   文件类型就应是 xxxContentType  真实文件名则应是xxxFileName
   

    // private String caption;
    public File[] getMyFile() {
        return myFile;
    }

    public void setMyFile(File[] myFile) {
        this.myFile = myFile;
    }

    public String[] getMyFileContentType() {
        return myFileContentType;
    }

    public void setMyFileContentType(String[] myFileContentType) {
        this.myFileContentType = myFileContentType;
    }

    public String[] getMyFileFileName() {
        return myFileFileName;
    }

    public void setMyFileFileName(String[] myFileFileName) {
        this.myFileFileName = myFileFileName;
    }

    private static String getExtention(String fileName) {
        int pos = fileName.lastIndexOf(".");
        return fileName.substring(pos);
    }

   
   
   
    private static void copy(File src, File dst) {
        System.out.println("000000   src dst "+src.getPath()+"   "+dst.getPath());
        try {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = new BufferedInputStream(new FileInputStream(src),
                        BUFFER_SIZE);
                out = new BufferedOutputStream(new FileOutputStream(dst),
                        BUFFER_SIZE);

                // 上传的最小文件不能小于 1 KB 否则会出现找不到文件的错误
                byte[] buffer = new byte[BUFFER_SIZE];
                while (in.read(buffer) > 0) {
                    out.write(buffer);
                }

            } finally {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 为了保证上传文件不会重名
    // 文件名以当前毫秒数保存
    private String saveFileName; // 以当前毫秒数为文件名

    public String uploadEssays() {
        for (int i = 0; i < myFile.length; i++) {
            saveFileName = new Date().getTime() + getExtention(myFileFileName[i]);
            // writeFile 就是以当前毫秒数为文件名的文件
            /*File writeFile = new File(ServletActionContext.getServletContext()
                    .getRealPath("/files")
                    + "/" + saveFileName);*/
            File writeFile=new File("D:/Workspaces8.6_J2EE/files/"+saveFileName);
            System.out.println("000000000   tmp "+myFile[i]);
            copy(myFile[i], writeFile);
        }
        return SUCCESS;
    }

}

!!!

(ServletActionContext.getServletContext().getRealPath("/files") 这里得到文件路径会因为操作系统不同而由变化
所以上传前线弄清楚到底位置在哪里  或者自己写一个确定的绝对路径

===============================================


原文地址:https://www.cnblogs.com/cart55free99/p/3495738.html