struts2 单个文件上传

本文介绍了一个使用Struts2框架实现文件上传的具体案例。通过展示upload.jsp页面代码及UploadAction.java后端处理逻辑,详细说明了如何设置文件上传字段、获取文件信息并将其保存至服务器指定目录的过程。

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

upload.jsp

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

<body>
        <form action="control/employee/list" method="post" enctype="multipart/form-data">
            文件:<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 {

        System.out.println("文件临时位置: " + upload);
        System.out.println("文件名称: " + uploadFileName);
        System.out.println("文件类型: " + uploadContentType);
        System.out.println("文件大小: " + upload.length());

        // 根据文件夹名称,获得服务器的真实路径
        String realPath = ServletActionContext.getServletContext().getRealPath(
                "images");
        // 根据文件夹路径构造出一个文件对象
        File saveFile = new File(realPath);
        // 如果文件路径不存在就创建文件夹
        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }
        if (null != upload) {
            // 将临时文件夹中的文件复制到指定的文件夹中
            FileUtils.copyFile(upload, new File(saveFile, uploadFileName));
            ActionContext.getContext().put("message", "上传文件成功");
        }
        return "success";
    }

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值