struts2 多文件上传

本文介绍了一个使用Struts2框架实现的多文件上传功能示例。通过一个简单的HTML表单,用户可以同时选择多个文件进行上传。该示例展示了如何在后台接收并处理这些文件,包括获取文件名、类型及大小等信息,并将它们保存到服务器指定目录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

upload.jsp

-----------------------------------------------------------------------------------------------------------------------------------

    <body>
        <form action="control/employee/list" method="post" enctype="multipart/form-data">
            文件1:<input type="file" name="upload"> <br />
            文件2:<input type="file" name="upload"> <br />
            文件3:<input type="file" name="upload"> <br />
            文件4:<input type="file" name="upload"> <br />
            <input type="submit" value="提交">
        </form>
    </body>

 

UploadAction.java

-----------------------------------------------------------------------------------------------------------------------------------

 

package org.taink.struts.action;

import java.io.File;
import java.io.IOException;

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

import com.opensymphony.xwork2.ActionContext;

public class UploadAction{
    private File[] upload;
    private String[] uploadContentType;
    private String[] uploadFileName;

    public void setUpload(File[] upload) {
        this.upload = upload;
    }

    public void setUploadContentType(String[] uploadContentType) {
        this.uploadContentType = uploadContentType;
    }

    public void setUploadFileName(String[] uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String execute() throws IOException {

        // 根据文件夹名称,获得服务器的真实路径
        String realPath = ServletActionContext.getServletContext().getRealPath(
                "upload");
        // 根据文件夹路径构造出一个文件对象
        File saveFile = new File(realPath);
        // 如果文件路径不存在就创建文件夹
        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }
        if (null != upload) {
            for (int i = 0; i < upload.length; i++) {
                System.out.println("文件临时位置: " + upload[i]);
                System.out.println("文件名称: " + uploadFileName[i]);
                System.out.println("文件类型: " + uploadContentType[i]);
                System.out.println("文件大小: " + upload[i].length());
                // 将临时文件夹中的文件复制到指定的文件夹中
                FileUtils.copyFile(upload[i], new File(saveFile, uploadFileName[i]));
            }
            ActionContext.getContext().put("message", "上传文件成功");
        }
        return "success";
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值