代码之家  ›  专栏  ›  技术社区  ›  Luk

如何检查文件是否通过Spring Rest Api完全下载

  •  2
  • Luk  · 技术社区  · 8 年前

    我已经创建了简单的RESTAPI来为来自HDF的文件提供服务(文件很大,我不想在本地复制它们)。

    我想记录信息,文件下载成功完成,即整个流被读取,但我不知道如何。我只能记录文件下载开始的信息。

        @Autowired
        private FileDownloadService fds;
    
        @RequestMapping(value = GET_FILE_PATH, method = RequestMethod.GET)
        @Produces(MediaType.APPLICATION_OCTET_STREAM_VALUE)
        public ResponseEntity getFileStream(@RequestParam("name") String name) {
            LOG.info("Processing for filename: " + name);
            try {
                Path p = fds.getFilePath(name);
                org.apache.hadoop.fs.FSDataInputStream is = fds.getFileStream(p);
    
                return ResponseEntity.ok().header("Content-Disposition", "attachment; filename=\"" + p.getName() + "\"'").contentLength(fds.getFileLength(p))
                        .contentType(MediaType.APPLICATION_OCTET_STREAM).body(new InputStreamResource(is));
    
            } catch (Exception e) {
                LOG.error(e.getLocalizedMessage(), e);
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error");
            } finally {
               LOG.info("File: " + name + " download started");
            }
        }
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   Andremoniy    8 年前

    您可以尝试在InputStream上创建包装器,并在流关闭时触发一些标志( close() ).

    ProxyInputStream

     ProxyInputStreamis = new ProxyInputStream(fds.getFileStream(p)) {
        @Override
        public void close() throws IOException {
                super.close();
                // some trigger
        }
     };