代码之家  ›  专栏  ›  技术社区  ›  Theophile Champion

在Spring应用程序中从运行Flask的API获取文件

  •  0
  • Theophile Champion  · 技术社区  · 6 年前

    API有一个路由 GET /zip_file/zip_name 使用flask返回zip文件 send_file

    Web应用程序必须允许用户下载此文件。

    我做到了:

        // Get the job's route url.
        String resourceUrl = ApiConfig.URL + "/" + ApiConfig.MODEL_ROUTE  + "/" + modelName;
    
        // Create the request.
        ClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        RestTemplate restTemplate = new RestTemplate(requestFactory);
    
        // Execute the request.
        ResponseEntity<String> res = restTemplate.getForEntity(resourceUrl, String.class);
    
        // Send the file to the user the returned zip file.
        String content = res.getBody();
        ByteArrayResource resource = new ByteArrayResource(content.getBytes());
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + modelName)
                .contentLength(content.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
    

    不幸的是,存档接收不是有效的。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Theophile Champion    6 年前

    可以直接返回从烧瓶接收到的响应:

    @GetMapping("/download_file")
    public ResponseEntity<ByteArrayResource> downloadFile(@RequestParam("file_name") String fileName, Model model) {
    
        // Get the job's route url.
        String resourceUrl = ApiConfig.URL + "/" + ApiConfig.FILE_ROUTE  + "/" + fileName;
    
        // Create the request.
        ClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        RestTemplate restTemplate = new RestTemplate(requestFactory);
    
        // Execute the request.
        return restTemplate.getForEntity(resourceUrl, ByteArrayResource.class);
    }