zoukankan      html  css  js  c++  java
  • js + java文件下载

    js请求:

    // 下载图片
        function oDownLoad(url, filename) {
            var url = '${pageContext.request.contextPath}/file/downFile.do?url=' + url + '&filename=' + encodeURI(filename);
            window.location.href = url;
        }

    java后端:

    @RequestMapping(value = "/downFile.do", method = RequestMethod.GET)
        public void downPicture(HttpServletRequest request, HttpServletResponse response) throws Exception {
            InputStream in = null;
            String url = request.getParameter("url");
            String filename = request.getParameter("filename");
            //filename = java.net.URLDecoder.decode(filename, "UTF-8");
            filename = new String(filename.getBytes("GB2312"),"iso-8859-1");
            try {
                URL httpUrl = new URL(url);
                HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(100000);// 连接超时单位毫秒 //
                conn.setReadTimeout(200000);// 读取超时 单位毫秒
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.connect();
    
                in = conn.getInputStream();
    
                byte[] bs = new byte[1024];
                int len = 0;
                response.reset();
    
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Cache-Control", "no-cache");
    
                response.setContentType("application/octet-stream");
                response.setHeader("Content-disposition", "attachment;filename=" + filename);
    
                ServletOutputStream out = response.getOutputStream();
                while ((len = in.read(bs))!= -1){
                    out.write(bs,0,len);
                }
    
                out.flush();
                //关流
                out.close();
            }catch (Exception e){
                throw new RuntimeException(url + "下载失败");
            }finally {
                try{
                    in.close();
                }catch (Exception e){
                }
            }
            
        }
  • 相关阅读:
    位运算
    LeetCode(230):二叉树中的第K小元素
    LeetCode(69):二分法求平方根
    TCP如何保证传输可靠性
    2种方法(递归+BFS)求二叉树的最小/最大深度
    自动生成Mapper文件(基于Mybatis Maven插件)
    Git的使用
    Java关键字及其作用详解
    Vagrant安装Centos/7
    java servlet 几种页面跳转的方法及传值
  • 原文地址:https://www.cnblogs.com/lovedaodao/p/11454293.html
Copyright © 2011-2022 走看看