文件的上传和下载

本文介绍如何使用Struts2框架实现文件的上传和下载功能。包括通过IO流进行文件上传的具体步骤,并展示了如何配置文件上传过滤器来限制文件类型和大小。此外,还详细解释了文件下载的方法。

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

一、文件的上传

// io流
String realPath = ServletActionContext.getServletContext().getRealPath("\\upload");
        // 输入流读取文件
        FileInputStream inputStream = new FileInputStream(file);
        // 创建一个文件对象
        File targetr = new File(realPath, fileFileName);
        // 创建一个输出流
        FileOutputStream outputStream = new FileOutputStream(targetr);
        byte[] bb = new byte[1024];
        int len;
        while ((len = inputStream.read(bb)) != -1) {
            outputStream.write(bb, 0, len);
        }
        outputStream.close();
        inputStream.close();

Struts2中的文件上传

public String upload() throws IOException {
        // io流
        String realPath = ServletActionContext.getServletContext().getRealPath("\\upload");
        // 创建一个文件对象
        File targetr = new File(realPath, fileFileName);

        FileUtils.copyFile(file, targetr);

        return SUCCESS;
    }

文件上传过滤器的设置

<!-- 添加文件上传拦截器 -->
            <interceptor-ref name="fileUpload">
            <!-- 设置允许上传的文件类型 -->
                <param name="allowedTypes">
                    image/jpeg,image/bmp
                </param>
                <!-- 设置允许上传的文件大小 -->
            <param name="maximumSize">81920</param>
            </interceptor-ref>
            <interceptor-ref name="defaultStack"/>

二、文件的下载

// 获取到要下载资源
        String realPath = ServletActionContext.getServletContext().getRealPath("\\download\\abc.txt");
        String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
        // 设置响应头
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Content-disposition", "attachment;fileName=" + filename);
        // 输入流
        FileInputStream inputStream = new FileInputStream(realPath);
        // 输出流
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] bb = new byte[1024];
        int len;
        while ((len = inputStream.read(bb)) != -1) {
            outputStream.write(bb, 0, len);

        }
        outputStream.close();
        inputStream.close();

struts2中的文件下载

public String streamDownLoad() throws IOException{
        // 获取到要下载的资源 的路径
        String realPath = ServletActionContext.getServletContext().getRealPath("\\download\\abc.txt");
        setInputStream(new FileInputStream(realPath));
        fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
        return Action.SUCCESS;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值