• SSM框架文件远程服务器下载


    1.首先你必须要建立连接

    获取URL的输入流

    2.之后就是文件读取和写入了

    3.还有就是设置响应头,响应码等

    代码

    @RequestMapping("/fileDownLoad")
        public HttpServletResponse fileDownLoad(@RequestParam("name") String name, HttpServletRequest request , HttpServletResponse response) throws Exception {
            String fileName = name;
            //连接远程服务器
    //        org.apache.commons.io.FileUtils.copyURLToFile(new URL("http://192.168.3.45/do-upload/component-factory/js/watch.1.3.1.js"), new File("watch.1.3.1.js"));
            String realPath = "http://localhost:8081/lvresourcems/uploadfiles/" + fileName;
            URL url = new URL(realPath);
            HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
            urlconn.connect();
            BufferedInputStream bis = null;
            ServletOutputStream os = null;
            bis = new BufferedInputStream(urlconn.getInputStream());
            os = response.getOutputStream();
            //InputStream in=urlconn.getInputStream();//将该文件加入到输入流之中
            byte b[] = new byte[2048];
            //客户使用保存文件的对话框:
            response.setHeader("Content-disposition", "inline;filename=" + fileName);
            //通知客户文件的MIME类型:
            response.setContentType("application/octet-stream exe;charset=gb2312");
    
            int size;
            //读取文件内容到缓存;
            while ((size = bis.read(b, 0, b.length)) != -1) {   //把文件内容写到本地文件中;
                //bos.write(b,0,size);
                os.write(b, 0, size);
            }
            os.close();
            bis.close();
    
    
    //        fileName=new String(fileName.getBytes("gbk"),"iso8859-1");//防止中文乱码
    //        HttpHeaders headers=new HttpHeaders();//设置响应头
    //        headers.add("Content-Disposition", "attachment;filename="+fileName);
    //        HttpStatus statusCode = HttpStatus.OK;//设置响应吗
    //        ResponseEntity<byte[]> response=new ResponseEntity<byte[]>(body, headers, statusCode);
            return response;
            //public ResponseEntity(T  body,
            //                       MultiValueMap < String,String > headers,
            //                       HttpStatus  statusCode)
            //HttpEntity使用给定的正文,标题和状态代码创建一个新的。
            //参数:
            //body - 实体机构
            //headers - 实体头
            //statusCode - 状态码
    
            }

    这是控制器代码,改一点就可以了

    世间种种的诱惑,不惊不扰我清梦
  • 相关阅读:
    springcloud(九):熔断器Hystrix和Feign的应用案例
    springcloud(八):熔断器Hystrix
    springcloud(七): 使用Feign调用Eureka Server客户端服务
    springcloud(六):给Eureka Server服务器端添加用户认证
    springcloud(六):Eureka提供数据的客户端连接Docker的mysql
    Live Reload
    localStorage eval script
    javascript AOP
    如何设置让SFTP的用户限制在某个目录下
    整站下载器
  • 原文地址:https://www.cnblogs.com/javalisong/p/9640307.html
Copyright © 2020-2023  润新知