SpringMVC下载文件

本文介绍了一个使用SpringBoot实现文件下载的示例代码。通过HttpSession获取服务器上指定路径的文件,并将其作为字节数组返回,同时设置了HTTP响应头以确保浏览器能够正确处理并下载文件。代码展示了如何利用Spring框架的ResponseEntity类来构造HTTP响应。

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

import org.junit.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class TestDownControlelr {


    @Test
    public ResponseEntity<byte[]> down(HttpSession session) throws IOException {

        //获取下载文件的路径
        String realPath = session.getServletContext().getRealPath("img");
        String finalPath = realPath + File.separator + "2.jpg";
        FileInputStream is = new FileInputStream(finalPath);
        //available(): 获取输入流所读取的文件的最大字节数
        byte[] b = new byte[is.available()];
        is.read(b);

        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition","attachment;filename=zzz.jpg");
        //设置响应状态
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(b, headers, statusCode);

        return entity;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值