SpringMVC之文件下载

本文介绍了一个使用Java实现的文件下载功能,通过Spring MVC框架的`ResponseEntity<byte[]>`返回文件内容给客户端。示例中详细展示了如何从服务器读取文件,并设置HTTP头部信息以触发浏览器的下载行为。

1.java代码:

@RequestMapping(value="fileDownLoad")
    public ResponseEntity<byte[]> testResponseEntity(HttpServletRequest request) throws Exception{
        //缓冲输入流
        byte[] body =null;
        //获取当前想买的真实路径
        ServletContext servletContext = request.getServletContext();
        String fileName = "JDBC数据库的增删查改.docx";
        //当前文件所在的真实路径
        String path = servletContext.getRealPath("/WEB-INF/"+fileName);
        //创建新文件
        File file = new File(path);
        InputStream in = new FileInputStream(file);
        //设置数组的大小
        body = new byte[in.available()];
        //读取文件
        in.read(body);
        HttpHeaders headers = new HttpHeaders();
        //获取文件名并解决乱码问题
        fileName = new String(fileName.getBytes("gbk"),"iso8859-1");
        headers.add("Content-Disposition", "attachment;filename="+fileName);
        HttpStatus statusCode=HttpStatus.OK;
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
        return response;
    }

2.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件下载</title>
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
</head>
<body>
    
    <a href="${pageContext.request.contextPath}/fileDownLoad">下载</a>
        
</body>
</html>

3.web文件配置与spring bean configuration file文件配置参照:http://www.cnblogs.com/TYDBLOG/p/7423103.html

4.相关包下载:(导入包时直接将文件复制到WEB-INF/lib文件夹下即可)

链接:http://pan.baidu.com/s/1hrYKLfu

密码:ixgj

5.文件上传参照:http://www.cnblogs.com/TYDBLOG/p/7423103.html

转载于:https://www.cnblogs.com/TYDBLOG/p/7424971.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值