下载文件方法

1、从hdfs下载文件流,主要原理是打开文件生成字节数组输出流,然后调用spring的ResponseEntity

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
    @Override
    public ResponseEntity<byte[]> download(DownloadRequest downloadRequest) throws IOException {
        List<ExportTaskVo> list = exportDAO.findExportTaskVoByUserTask3(
                downloadRequest.getUserId(),
                downloadRequest.getTaskId(),
                downloadRequest.getTaskStartTS()
        );

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        HttpHeaders headers = new HttpHeaders();
        // 文件的属性,也就是文件叫什么吧
        headers.setContentDispositionFormData("attachment", "blank");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        if (list != null && !list.isEmpty()) {
            ExportTaskVo taskVo = list.get(0);
            HDFSUtils.initHDFS(hdfsURI, hdfsUser);
            if (StringUtils.isEmpty(taskVo.getFileName())) {
                logger.error("filePath 为空");
                return null;
            }
            HDFSUtils.httpDownLoad(taskVo.getFileName(), bos);
            String filePath = taskVo.getFileName();
            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            logger.info("fileName:" + fileName);
            headers.setContentDispositionFormData("attachment", fileName);
        }
       ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bos.toByteArray(), headers, HttpStatus.OK);
        bos.close();
        return responseEntity;
上一篇:高效开发:Mybatis中useGeneratedKeys的用法


下一篇:RestTemplate的基本使用