struts2 文件上传 三种方式

struts.multipart.maxSize=10240000:用于限制上传文件的大小
struts.multipart.allowedTypes=.xls,.zip:用于限制上传文件类型
struts.multipart.parser=pell:解决上传空文件的报错问题

struts.multipart.saveDir:该属性指定上传文件的临时保存路径,该属性的默认值是javax.servlet.context.tempdir

第一种方式

package com.ljq.action;

import java.io.File;

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

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class UploadAction extends ActionSupport{

    private File[] image; //上传的文件
    private String[] imageFileName; //文件名称
    private String[] imageContentType; //文件类型

    public String execute() throws Exception {
        ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
        String realpath = ServletActionContext.getServletContext().getRealPath("/images");
        System.out.println(realpath);
        if (image != null) {
            File savedir=new File(realpath);
            if(!savedir.getParentFile().exists())
                savedir.getParentFile().mkdirs();
            for(int i=0;i<image.length;i++){
                File savefile = new File(savedir, imageFileName[i]);
                FileUtils.copyFile(image[i], savefile);
            }
            ActionContext.getContext().put("message", "文件上传成功");
        }
        return "success";
    }

    public File[] getImage() {
        return image;
    }

    public void setImage(File[] image) {
        this.image = image;
    }

    public String[] getImageContentType() {
        return imageContentType;
    }

    public void setImageContentType(String[] imageContentType) {
        this.imageContentType = imageContentType;
    }

    public String[] getImageFileName() {
        return imageFileName;
    }

    public void setImageFileName(String[] imageFileName) {
        this.imageFileName = imageFileName;
    }

}

                   

第二种方式

package com.ljq.action;

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

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
/**
 * 使用数组上传多个文件
 *
 * @author ljq
 *
 */
@SuppressWarnings("serial")
public class UploadAction2 extends ActionSupport{
    private File[] image; //上传的文件
    private String[] imageFileName; //文件名称
    private String[] imageContentType; //文件类型
    private String savePath;

    @Override
    public String execute() throws Exception {
        ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
        //取得需要上传的文件数组
        File[] files = getImage();
        if (files !=null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                //建立上传文件的输出流, getImageFileName()[i]
                System.out.println(getSavePath() + "\\" + getImageFileName()[i]);
                FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + getImageFileName()[i]);
                //建立上传文件的输入流
                FileInputStream fis = new FileInputStream(files[i]);
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len=fis.read(buffer))>0) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
                fis.close();
            }
        }
        return SUCCESS;
    }

    public File[] getImage() {
        return image;
    }

    public void setImage(File[] image) {
        this.image = image;
    }

    public String[] getImageFileName() {
        return imageFileName;
    }

    public void setImageFileName(String[] imageFileName) {
        this.imageFileName = imageFileName;
    }

    public String[] getImageContentType() {
        return imageContentType;
    }

    public void setImageContentType(String[] imageContentType) {
        this.imageContentType = imageContentType;
    }

    /**
     * 返回上传文件保存的位置
     *
     * @return
     * @throws Exception
     */
    public String getSavePath() throws Exception {
        return ServletActionContext.getServletContext().getRealPath(savePath);
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

}

            

第三种方式

package com.ljq.action;

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

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 * 使用List上传多个文件
 *
 * @author ljq
 *
 */
@SuppressWarnings("serial")
public class UploadAction3 extends ActionSupport {
    private List<File> image; // 上传的文件
    private List<String> imageFileName; // 文件名称
    private List<String> imageContentType; // 文件类型
    private String savePath;

    @Override
    public String execute() throws Exception {
        ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
        // 取得需要上传的文件数组
        List<File> files = getImage();
        if (files != null && files.size() > 0) {
            for (int i = 0; i < files.size(); i++) {
                FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + getImageFileName().get(i));
                FileInputStream fis = new FileInputStream(files.get(i));
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = fis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fis.close();
                fos.close();
            }
        }
        return SUCCESS;
    }

    public List<File> getImage() {
        return image;
    }

    public void setImage(List<File> image) {
        this.image = image;
    }

    public List<String> getImageFileName() {
        return imageFileName;
    }

    public void setImageFileName(List<String> imageFileName) {
        this.imageFileName = imageFileName;
    }

    public List<String> getImageContentType() {
        return imageContentType;
    }

    public void setImageContentType(List<String> imageContentType) {
        this.imageContentType = imageContentType;
    }

    /**
     * 返回上传文件保存的位置
     *
     * @return
     * @throws Exception
     */
    public String getSavePath() throws Exception {
        return ServletActionContext.getServletContext().getRealPath(savePath);
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

}

              

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>
    <!-- 该属性指定需要Struts2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts2处理。
        如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。 -->
    <constant name="struts.action.extension" value="do" />
    <!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 -->
    <constant name="struts.serve.static.browserCache" value="false" />
    <!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 -->
    <constant name="struts.configuration.xml.reload" value="true" />
    <!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->
    <constant name="struts.devMode" value="true" />
    <!-- 默认的视图主题 -->
    <constant name="struts.ui.theme" value="simple" />
    <!--<constant name="struts.objectFactory" value="spring" />-->
    <!--解决乱码    -->
    <constant name="struts.i18n.encoding" value="UTF-8" />
    <constant name="struts.multipart.maxSize" value="10701096"/>

    <package name="upload" namespace="/upload" extends="struts-default">
        <action name="*_upload" class="com.ljq.action.UploadAction" method="{1}">
            <result name="success">/WEB-INF/page/message.jsp</result>
        </action>
    </package>
    <package name="upload1" namespace="/upload1" extends="struts-default">
        <action name="upload1" class="com.ljq.action.UploadAction2" method="execute">
            <!-- 要创建/image文件夹,否则会报找不到文件 -->
            <param name="savePath">/image</param>
            <result name="success">/WEB-INF/page/message.jsp</result>
        </action>
    </package>
    <package name="upload2" namespace="/upload2" extends="struts-default">
        <action name="upload2" class="com.ljq.action.UploadAction3" method="execute">
            <!-- 要创建/image文件夹,否则会报找不到文件 -->
            <param name="savePath">/image</param>
            <result name="success">/WEB-INF/page/message.jsp</result>
        </action>
    </package>
</struts>

           

上传表单页面upload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>文件上传</title>

        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
    </head>

    <body>
        <!-- ${pageContext.request.contextPath}/upload/execute_upload.do -->
        <!-- ${pageContext.request.contextPath}/upload1/upload1.do -->
        <!-- ${pageContext.request.contextPath}/upload2/upload2.do -->
        <!--  -->
        <form action="${pageContext.request.contextPath}/upload2/upload2.do" enctype="multipart/form-data" method="post">
            文件1:<input type="file" name="image"><br/>
            文件2:<input type="file" name="image"><br/>
            文件3:<input type="file" name="image"><br/>
                <input type="submit" value="上传" />
        </form>
    </body>
</html>

显示页面message.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

    <title>My JSP 'message.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
  </head>

  <body>
    上传成功
  <br/>
  <s:debug></s:debug>
时间: 2024-09-13 07:29:00

struts2 文件上传 三种方式的相关文章

关于struts2文件上传和保存到数据库的同步问题!急~

问题描述 利用struts2文件上传后,对文件信息保存到数据库.文件上传成功后,对文件信息进行保存,失败则不保存.问题就在于如果文件上传成功后,对数据库保存失败,那么该如何保持事务的准确性.目前相到两种解决方法:1.建立temp临时文件夹,当保存数据库成功,则copy文件到正式目录,不论文件上传成功失败,最后删除temp.(麻烦)2.使用异步对文件进行操作.(不大清楚实现逻辑)希望大家能给我提供方案.谢谢~ 解决方案 先插入数据,成功则保存文件,不成功则不进行处理不就可以了么解决方案二:同意ji

java中Struts2文件上传问题详解_java

首先是网页部分,upload_file.jsp <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <html> <head> <title>Upload File</title> </head> <body> <form act

8、如何自学Struts2之Struts2文件上传[视频]

8.如何自学Struts2之Struts2文件上传[视频]   之前写了一篇"打算做一个视频教程探讨如何自学计算机相关的技术",优酷上传不了,只好传到百度云上:   http://pan.baidu.com/s/1kTDsa95 由于本次视频没有声音,将会在下节课"Struts2数据库访问"这一节课,一起再讲一下. 注意:不好意思,不知道为什么在这次录制过程中没有声音,很抱歉,本节重点是碰到一个空指针异常,原因是fileUpload这个拦截器要放在其他拦截器之前才没

关于Struts2文件上传与自定义拦截器_java

一.访问或添加request/session/application属性 public String scope() throws Exception{   ActionContext ctx = ActionContext.getContext();   ctx.getApplication().put("app", "应用范围");//往ServletContext里放入app   ctx.getSession().put("ses", &q

SSH框架网上商城项目第13战之Struts2文件上传功能_java

上一节我们做完了添加和更新商品的功能,这两个部分里有涉及到商品图片的上传,并没有详细解说.为此,这篇文章详细介绍一下Struts2实现文件上传的功能.1. 封装文件信息我们首先得有一个Model来封装文件的信息,这个Model里需要有三个属性:文件.文件类型和文件名.针对我们要传的图片,我们新建一个Model如下: public class FileImage { private File file; private String contentType; private String file

struts2 文件上传时,某次上传失败之后的所有上传都返回input,不跳到action

问题描述 在做文件上传时,不加限制上传任意类型文件都成功,但是如果加了"allowedTypes"限制文件类型后,上传正确类型成功,上传错误类型失败,这些都是理所当然的结果.问题是上传错误类型失败后,再上传正确的文件,也跳转到input视图,不经过action.如限制只能上传gif格式文件,第一次上传gif图片返回success:第二次上传非gif文件,返回input:第三次上传gif文件,还是返回input,怎么解决?代码如下:jsp页面: <s:form action =&q

新手求助,struts2文件上传的错误

问题描述 我在跑这段代码的时候遇到了java.lang.NullPointerException错误,代码和错误如下.可是如果我把execute函数改为直接返回SUCCESS就没有错误了,希望各位大神能帮帮我,谢谢了~publicclassUploadActionextendsActionSupport{//封装文件标题请求参数的属性privateStringtitle;//封装上传文件域的属性privateFileupload;//封装上传文件类型的属性privateStringuploadC

struts2 文件上传程序代码

简介 由于今天做个一个项目有关文件上传内容,业务逻辑是这样的,选择一个文件上传到服务器,然后把文件名称,上传时间,上传用户以及备注存储到服务器,并且提供一个web页面进行管理. 开发环境: 架构:使用struts2+mybatis框架,以及前台使用easyUI框架进行开发. 数据库:mysql 前台html代码: 注意: 在编写form 表单的时候一定要注意加上这句话 ==enctype="multipart/form-data"==,声明此表单可以上传文件,在开发中很容易遗漏,以至于

Struts2文件上传(一) Common-FileUpload

文件上传是许多项目都遇到的需求,Struts2中也带有文件上传功能,但它是利用的java领域的其他 俩个常用的文件上传的项目:Common- FileUpload和COS,在了解Struts2之前让我们了解下怎样使用 Common-FileUpload来实现文件上传以及文件上传实现过程中应该注意的问题. 在Common- FileUpload中,它把从客户端提交过来的表单封装成一个个FileItem对象,这也是它实现文件上传功能 的核心类.另一个很重要的类就是FileUploadBase,他的功