• 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 - 状态码
    
            }

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

    世间种种的诱惑,不惊不扰我清梦
  • 相关阅读:
    Mybatis源代码分析之类型转换
    eclipse中对于@override注解的函数报父类没有该方法
    Mybatis源代码分析之metadata包
    Android GC
    有道单词本导出xml转换.
    广播的接收与U盘广播
    Bitmap和Drawable相互转换方法
    如何提交程序到Android Market
    error parsing xml:unbound prefix
    android获取屏幕尺寸、密度
  • 原文地址:https://www.cnblogs.com/javalisong/p/9640307.html
Copyright © 2020-2023  润新知