首页 > 代码库 > java struts2 上传文件范例

java struts2 上传文件范例

Struts2 default.properites属性文件相关说明

struts.i18n.encoding=UTF-8 国际化默认编码格式为UTF-8

struts.objectFactory = spring spring整合时需要使用

 

### Parser to handle HTTP POST requests, encoded using the MIME-type multipart/form-data

# struts.multipart.parser=cos

# struts.multipart.parser=pell

struts.multipart.parser=Jakarta 使用apache提供的文件上传也下载

 

struts.action.extension=action,, 这时就是我们提交表单后缀名为.action的原因

struts.devMode = false  是否设置为开发者模式

struts.i18n.reload=false 设置资源文件是否每次缓存

struts.configuration.xml.reload=false 设置struts.xml修改是否每次自动加载

 

 

Struts2 文件上传

进行文件上传时,必须将表单的method属性设为post,将enctype属性设为multipart/form-data。

Struts2在进行文件上传操作时,实际上是通过两个步骤实现的:

1) 首先将客户端上传的文件保存到struts.multipart.saveDir键所指定的目录中,如果该键所对应的目录不存在,那么就保存到javax.servlet.context.tempdir环境变量所指定的目录中。

2) Action中所定义的File类型的成员变量file实际上指向的是临时目录中的临时文件,然后在服务器端通过IO的方式将临时文件写入到指定的服务器端目录中。

 

OGNL(Object Graph Navigation Language):对象图导航语言。

Struts2的文件上传实际上是通过FileUploadInterceptor拦截器来处理的。

 

源码展示:

 1 <%@ page language="java" contentType="text/html; charset=utf-8"
 2     pageEncoding="utf-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 7 <title>文件上传</title>
 8 </head>
 9 <body>
10     <form action="upload.action" method="post" enctype="multipart/form-data">
11         username:<input type="text" name="username"><br>
12         file:<input type="file" name="file"><br>
13         <input type="submit" value="http://www.mamicode.com/提交">
14     </form>
15 </body>
16 </html>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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>文件上传</title>
</head>
<body>
    <form action="uploadListAction" method="post" enctype="multipart/form-data">
        username:<input type="text" name="username"><br>
        file:<input type="file" name="file"><br>
        file2:<input type="file" name="file"><br>
        file3:<input type="file" name="file"><br>
        <input type="submit" value="http://www.mamicode.com/提交">
    </form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
    <a href="http://www.mamicode.com/downloadFile1.action?number=1">下载文件</a>
    <a href="http://www.mamicode.com/downloadFile1.action?number=2">下载文件</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
    <a href="http://www.mamicode.com/downloadFile.action">下载文件</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="/struts-tags" prefix="s" %>
<!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>
    用户 名:<s:property value="http://www.mamicode.com/username"/><br>
    <s:iterator value="http://www.mamicode.com/fileFileName" id="fe">
        file:<s:property value="http://www.mamicode.com/#fe.toUpperCase()"/>
    </s:iterator>
    
    <!-- 
        我们的集合中有如下的信息List<Person> list;
        在我们的Person对象中还有一个Cat 
        Person 
        下private Cat cat;
        
        <s:iterator value="http://www.mamicode.com/list" id="list">
        <s:property value="http://www.mamicode.com/#list.name"/>人类的名字
        <s:property value="http://www.mamicode.com/#list.cat.name"/>人类的名字
        
        
        
    </s:iterator>
     -->
    
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
    文件上传成功!
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>struts_021</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    <filter>
        <filter-name>strtus2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>strtus2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

技术分享

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
    "http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
    <package name="struts" extends="struts-default" namespace="/">
        <action name="upload" class="com.oracle.action.UploadAction">
            <result name="success">/result.jsp</result>
        </action>
        <action name="uploadListAction" class="com.oracle.action.UploadListAction">
            <result name="success">/Listresult.jsp</result>
        </action>
        <action name="downloadFile" class="com.oracle.action.DownloadAction">
            <result name="success" type="stream">
                <param name="contentDisposition">attachment;filename="test.txt"</param>
                <param name="inputName">downloadFile</param>
            </result>
        </action>
        <action name="downloadFile1" class="com.oracle.action.DownloadAction1">
            <result name="success" type="stream">
                <param name="contentDisposition">attachment;filename=${filename}</param>
                <param name="inputName">downloadFile</param>
            </result>
        </action>
    </package>
</struts>
struts.multipart.saveDir=c:/test
struts.multipart.maxSize=193439403840844
package com.oracle.action;

import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class DownloadAction extends ActionSupport {
    //DownloadFile这里的名字需要与我们的struts.xml中的名字一样
    public InputStream getDownloadFile() {
        // 将资源以流的形式返回
        return ServletActionContext.getServletContext().getResourceAsStream(
                "/upload/test.txt");
    }

    @Override
    public String execute() throws Exception {
        return SUCCESS;
    }
}
package com.oracle.action;

import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class DownloadAction1 extends ActionSupport {
    private int number;
    private String filename;

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public InputStream getDownloadFile() {
        try {
            if (1 == number) {
                this.filename = "你好.txt";

                this.filename = new String(this.filename.getBytes("gbk"), "8859_1");

                return ServletActionContext.getServletContext().getResourceAsStream("/upload/你好.txt");
            } else {
                this.filename = "test.txt";

                return ServletActionContext.getServletContext().getResourceAsStream("/upload/test.txt");
            }
        } catch (Exception ex) {

        }

        return null;
    }

    @Override
    public String execute() throws Exception {
        return SUCCESS;
    }
}
package com.oracle.action;

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;

/**
 * 
 * @author Mountainpeople
 * 
 */
public class UploadAction extends ActionSupport {
    // 表单的名字
    private String username;
    // 临时文件
    private File file;// file必须要与我们的页面中的一样
    // 得到文件的名字[FileName]
    private String fileFileName;//file必须与页面中的一样 FileName必须这样的写法

    // 得到文件的内容类型[ContentType]
    private String fileContentType;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    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;
    }

    @Override
    public String execute() throws Exception {
        // 完成文件的上传
        // 存放文件的路径
        String root = ServletActionContext.getRequest().getRealPath("/upload");
        // 写入文件的路径
        // 得到输入流对象
        InputStream is = new FileInputStream(file);
        // 创建File对象
        File destFile = new File(root, fileFileName);
        // 得到输出流对象
        OutputStream os = new FileOutputStream(destFile);
        // 创建字节流对象
        byte[] buffer = new byte[500];
        int length = 0;
        while ((length = is.read(buffer)) != -1) {
            os.write(buffer, 0, length);
        }
        // 操作完成关闭对象
        is.close();
        os.close();
        return SUCCESS;
    }
}
package com.oracle.action;

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

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 * 
 * @author Mountainpeople
 * 
 */
public class UploadListAction extends ActionSupport {
    private String username;
    private List<File> file;
    // 得到文件的名字[FileName]
    private List<String> fileFileName;

    // 得到文件的内容类型[ContentType]
    private List<String> fileContentType;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public List<File> getFile() {
        return file;
    }

    public void setFile(List<File> file) {
        this.file = file;
    }

    public List<String> getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(List<String> fileFileName) {
        this.fileFileName = fileFileName;
    }

    public List<String> getFileContentType() {
        return fileContentType;
    }

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

    @Override
    public String execute() throws Exception {

        for (int i = 0; i < file.size(); i++) {
            // 完成文件的上传
            // 存放文件的路径
            String root = ServletActionContext.getRequest().getRealPath(
                    "/upload");
            // 写入文件的路径
            // 得到输入流对象
            InputStream is = new FileInputStream(file.get(i));
            // 创建File对象
            File destFile = new File(root, fileFileName.get(i));
            // 得到输出流对象
            OutputStream os = new FileOutputStream(destFile);
            // 创建字节流对象
            byte[] buffer = new byte[500];
            int length = 0;
            while ((length = is.read(buffer)) != -1) {
                os.write(buffer, 0, length);
            }
            // 操作完成关闭对象
            is.close();
            os.close();
        }

        return SUCCESS;
    }
}

 

java struts2 上传文件范例