下载文件,不传HttpResponse,如何改写呢

问题:如题

    public void download(HttpServletResponse response, String file) throws IOException {

        Path path = Paths.get(filePath, file).normalize();

        // 文件不存在,或者目标文件是目录
        if (Files.notExists(path) || Files.isDirectory(path)) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }

        // 尝试获取文件的ContentType
        String mediaType = Files.probeContentType(path);

        if (mediaType == null) {
            // 获取失败,使用通用的二进制文件类型
            mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        }

        // Content-Type
        response.setHeader(HttpHeaders.CONTENT_TYPE, mediaType);
        // Content-Disposition
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment()
                .filename(path.getFileName().toString(), StandardCharsets.UTF_8).build().toString());
        // Content-Length
        response.setContentLengthLong(Files.size(path));

        Files.copy(path, response.getOutputStream());
    }

HttpServletResponse咋下载?你可以考虑用spring的ResponseEntity

1 Like