模拟本地服务为文件服务器(两种提供方式):假设本地文件为服务器,提供文件获取服务

方法一:直接将输出流放入response里面作为响应

@RequestMapping(value = "/getUrlDownload",method = RequestMethod.GET)
    @ResponseBody
    public void getUrlDownload(HttpServletResponse response) {
        String url = "C:\\user.zip";
        File file = new File(url);
        //判断文件是否存在如果不存在就进行异常处理
        if (!(file.exists() && file.canRead())) {
            System.out.println("文件不存在");
        }
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            int length = inputStream.read(data);
            inputStream.close();
            OutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();
            stream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

方法二:将输入流放入ResponseEntity的body里面,并做返回

String separator = File.separator;
 
    @RequestMapping(value = "/download", method = RequestMethod.GET, produces ="application/json;charset=UTF-8")
    @ResponseBody
    public ResponseEntity<InputStreamResource> download() {
 
        String newName = "2";
        String route = "download" + File.separator + "templates" + File.separator;
        String path = null;
        ResponseEntity<InputStreamResource> response = null;
        try {
            path = "download" + separator + "bst.zip";
            ClassPathResource classPathResource = new ClassPathResource(path);
            InputStream inputStream = classPathResource.getInputStream();
            response = ResponseEntity.ok()
                    .body(new InputStreamResource(inputStream));
        } catch (FileNotFoundException e1) {
            System.out.println(e1.getMessage());
//            log.error("找不到指定的文件", e1);
        } catch (IOException e) {
            System.out.println(e.getMessage());
//            log.error("获取不到文件流", e);
        }
 
        return response;
    }

以上两种方式皆可做文件服务器,提供给其他服务获取文件,这里注意与文件下载并不一样,都是以流的形式返回或者响应。而文件下载是将服务器的文件下载到本地,接下来演示远程文件下载代码。

远程获取文件(两种方式):

方式一:RestTemplate 获取,如下代码:

 @RequestMapping(value = "/getf", method = RequestMethod.GET, produces ="application/json;charset=UTF-8")
    @ResponseBody
    public void getf() throws URISyntaxException {
        String url = "http://localhost:8888/file/download";
        RequestEntity build = RequestEntity.get(new URI(url)).build();
        RestTemplate restTemplate  =new RestTemplate();
        ResponseEntity<byte[]> exchange = restTemplate.exchange(build, byte[].class);
        byte[] body = exchange.getBody();
 
        String fileName = "xxxx.zip";
        String filePath = "src/main/resources/templates/";
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if(!dir.exists() && !dir.isDirectory()){//判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(body);
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }

方式二:URL获取,代码如下:

  @RequestMapping(value = "/getFile", method = RequestMethod.GET, produces ="application/json;charset=UTF-8")
    @ResponseBody
    public void getFile() {
        String filePath = "http://localhost:8888/file/getUrlDownload";
        //定义文件名
        String fileName = "111.zip";
 
//定义要保存的文件路径
        String savePath = "/resources/templates/"+fileName;
        File file = new File(savePath);
 
//如果文件目录不出在则创建目录 *getParentFile()*
        if (!file.getParentFile().exists()) {
            //判断文件目录是否存在
            file.getParentFile().mkdirs();//创建目录
        }
 
        try {
            URL url = new URL(filePath);
            //字节输入流
            InputStream is = url.openStream();
            //字节流转字符流
 
            DataInputStream dataInputStream = new DataInputStream(is);
                                                    转化流
            FileOutputStream fileOutputStream = new FileOutputStream(file);
 
            //使用char 数组传输    -----字节流byte数组
            byte[] chs = new byte[1024];
            //标记
            int len = 0;
            while ((len = dataInputStream.read(chs)) != -1) {
                // read() 方法,读取输入流的下一个字节,返回一个0-255之间的int类型整数。如果到达流的末端,返回-1
 
                fileOutputStream.write(chs,0,len);
            }
            fileOutputStream.close();
            dataInputStream.close();
 
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
 
        }
    }

以上两种皆可远程获取到文件服务器的文件,只是方式不一样,但是获取本质都是以流的形式获取到,转换为byte[] 数组,最终写出来。方法二中有一个注意点,write方法重载有三个write(int a)、write(byte[] by,int begin,int end)、write(byte[] by),这里一般用write(byte[] by,int begin,int end),可保证下载文件正常打开,zip、rar文件打开时不会遇到:不可预测的文件尾部 ,这样的异常信息,其次是在以上方式中并没有添加中文乱码情况,可做补充。

原文地址:http://www.cnblogs.com/fuqian/p/16820210.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性