【问题标题】:how to downlod file using resttemplate如何使用resttemplate下载文件
【发布时间】:2022-01-28 11:10:42
【问题描述】:
        String uri = "URL";
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());    
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
        HttpEntity<String> entity = new HttpEntity<String>(headers);

        ResponseEntity<byte[]> response = restTemplate.exchange(uri, HttpMethod.GET, entity, byte[].class, "1");

我收到类似的响应-> 我想下载 (935436242330664960_pratikpopo.txt) 这个文件。 有什么方法可以下载这个文件

【问题讨论】:

  • 看看这是否有帮助 - stackoverflow.com/a/26615303/17981941
  • 欢迎来到 StackOverflow。您能否详细说明什么不起作用?
  • 我收到此回复,但我无法下载 pratikpopo.txt 文件下载。我的动机是将此文件存储在本地机器中我们应该怎么做

标签: java spring-boot rest resttemplate


【解决方案1】:
{
        URL link = new URL("your full url http://........");
        InputStream in = new BufferedInputStream(link.openStream());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int n = 0;
        while (-1!=(n=in.read(buf)))
        {
           out.write(buf, 0, n);
        }
        out.close();
        in.close();
        byte[] response = out.toByteArray();
        
        FileOutputStream fos = new FileOutputStream("C:/download-file/YourFileName.txt");
        fos.write(response);
        fos.close();
 }

【讨论】:

    【解决方案2】:
      @RequestMapping(value = "/download3/{path}", method = RequestMethod.GET)
        public String downloadFile4( @RequestParam("file_name") String path) throws IOException
        {
            String uri = "File Path-URL(location wehere your file is stored on server)";
            RestTemplate restTemplate = new RestTemplate();
            restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());    
            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
            HttpEntity<String> entity = new HttpEntity<String>(headers);
    
            ResponseEntity<byte[]> response = restTemplate.exchange(uri, HttpMethod.GET, entity, byte[].class, "1");
            
            URL furl = new URL(uri);
            ReadableByteChannel rbc = Channels.newChannel(furl.openStream());
            FileOutputStream fos = new FileOutputStream("C:/download-file/"+ response.getHeaders().getContentDisposition().getFilename());
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            
            return "file downloaded";
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      • 2013-03-24
      • 1970-01-01
      • 2016-11-27
      • 1970-01-01
      • 2015-02-07
      • 2011-10-10
      相关资源
      最近更新 更多