java请求响应浏览器一个下载文件

首先html不能使用ajax提交,得使用form表单提交,要么使用location.href="";这种方式提交 

<%--
  Created by IntelliJ IDEA.
  User: kxj
  Date: 2019/9/11
  Time: 17:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<jsp:include page="${pageContext.request.contextPath}/common/common.jsp"/>
<body>
<form action="${pageContext.request.contextPath}/ZSCommodity/download">
    <input type="submit" value="下载">
</form>

</body>
</html>

Controller方法

 @ResponseBody
    @RequestMapping("download")
    public String download(HttpServletRequest request,HttpServletResponse response){
        String url = "D:\\Documents\\Desktop\\aa.txt";
        File fileurl = new File(url);
        //浏览器下载后的文件名称showValue,从url中截取到源文件名称以及,以及文件类型,如board.docx;
        String showValue = "bb.txt";
        //System.out.println(showValue);
        try{
            //根据条件得到文件路径
           // System.out.println("===========文件路径==========="+fileurl);
            //将文件读入文件流
            InputStream inStream = new FileInputStream(fileurl);
            //获得浏览器代理信息
            final String userAgent = request.getHeader("USER-AGENT");
            //判断浏览器代理并分别设置响应给浏览器的编码格式
            String finalFileName = null;
            if(StringUtils.contains(userAgent, "MSIE")||StringUtils.contains(userAgent,"Trident")){//IE浏览器
                finalFileName = URLEncoder.encode(showValue,"UTF8");
                System.out.println("IE浏览器");
            }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
                finalFileName = new String(showValue.getBytes(), "ISO8859-1");
            }else{
                finalFileName = URLEncoder.encode(showValue,"UTF8");//其他浏览器
            }
            //设置HTTP响应头
            response.reset();//重置 响应头
            response.setContentType("application/x-download");//告知浏览器下载文件,而不是直接打开,浏览器默认为打开
            response.addHeader("Content-Disposition" ,"attachment;filename=\"" +finalFileName+ "\"");//下载文件的名称

            // 循环取出流中的数据
            byte[] b = new byte[1024];
            int len;
            while ((len = inStream.read(b)) > 0){
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
            response.getOutputStream().close();
        }catch(Exception e) {
            e.printStackTrace();
        }
        return "";
    }

然后点击下载就下载成功了.

批量下载,得把所有文件压缩到一个压缩包中,然后统一下载,因为response中的流close后浏览器才会响应下载,但是只能close一次,所以只能使用压缩包的方式


		List<String> list2 = new ArrayList<>();

		list2.add("group1/M00/00/2F/rB9El1-YyJOANIzSAACTMe0YRxc2878106");
		list2.add("group1/M00/00/2F/rB9El1-YyM2APMPTAAAxoWioF9A2502458");

		int i = 1;
		// 创建临时压缩文件

		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ZipOutputStream zos = new ZipOutputStream(bos);
		ZipEntry ze = null;
		for (String url : list2) {//将所有需要下载的pdf文件都写入临时zip文件
			//BufferedInputStream bis = new BufferedInputStream(new FileInputStream(files[i]));
			ze = new ZipEntry("文件"+i+".jpg");  //压缩包中当前文件的名称
			zos.putNextEntry(ze);
			byte[] bytes = fastDFSHelper.downloadFile(url);  //把当前文件的流写入到压缩包当中.
			zos.write(bytes);
			i++;
		}
		zos.flush();
		zos.close();

		//下载文件的名称
		response.setContentType("application/x-download");
		response.addHeader("Content-Disposition" ,"attachment;filename=\"文件.zip\"");
		response.getOutputStream().write(bos.toByteArray());
		response.getOutputStream().close();

实现一边往文件写内容,一边下载

    //实现文件下载功能
    @RequestMapping("/downloadScheme/{filename:.+}")
    public void downloadFile(@PathVariable String filename, HttpServletResponse response, HttpServletRequest request) throws Exception{

        new Thread(()->{
            File file = new File("e:\\test.txt");
            FileOutputStream fop;
            int i=0;
            try {
                fop = new FileOutputStream(file);
                if (!file.exists()) {
                    file.createNewFile();
                }

                while (i<50){
                    //将字符串转成字节
                    byte[] contentInBytes = "123\r\n".getBytes();
//写入文件
                    fop.write(contentInBytes);
                    fop.flush();
                    i++;
                    Thread.sleep(500);
                }
//释放
                fop.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        Thread.sleep(2000);
        //浏览器下载后的文件名称showValue,从url中截取到源文件名称以及,以及文件类型,如board.docx;
        String showValue = "bb.txt";
        //System.out.println(showValue);
        try{
            //根据条件得到文件路径
            // System.out.println("===========文件路径==========="+fileurl);
            //将文件读入文件流
            InputStream inStream = new FileInputStream("e:\\test.txt");
            //获得浏览器代理信息
            final String userAgent = request.getHeader("USER-AGENT");
            //判断浏览器代理并分别设置响应给浏览器的编码格式
            String finalFileName = null;
            if(StringUtils.contains(userAgent, "MSIE")||StringUtils.contains(userAgent,"Trident")){//IE浏览器
                finalFileName = URLEncoder.encode(showValue,"UTF8");
                System.out.println("IE浏览器");
            }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
                finalFileName = new String(showValue.getBytes(), "ISO8859-1");
            }else{
                finalFileName = URLEncoder.encode(showValue,"UTF8");//其他浏览器
            }
            //设置HTTP响应头
            response.reset();//重置 响应头
            response.setHeader("Accept-Ranges", "bytes");
            response.setContentType("application/x-download");//告知浏览器下载文件,而不是直接打开,浏览器默认为打开
            response.addHeader("Content-Disposition" ,"attachment;filename=\"" +finalFileName+ "\"");//下载文件的名称

            // 循环取出流中的数据
            byte[] b = new byte[1024];
            int len;
            while ((len = inStream.read(b)) > 0){
                Thread.sleep(2000);
                ServletOutputStream outputStream = response.getOutputStream();
                outputStream.write(b, 0, len);
                outputStream.flush();
            }
            inStream.close();
            response.getOutputStream().close();
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值