【Java】文件下载【Java】檔案下載

前言

通过将文件转换为二进制形式,并将其设置为响应内容,以实现文件下载。有两种方法可以实现。

将二进制数据设置到响应(Controller方法的返回值)中。
将二进制数据设置到响应(方法的参数/HttpServletResponse)中。

提供参考

将二进制数据设置为响应(控制器方法的返回值)。

 

将二进制数据设置到响应中(作为方法的参数/HttpServletResponse)。

 

① 将二进制数据设置为响应(Controller方法的返回值)。

源代码

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/files")
public class FileController {
    @GetMapping("/downloadFile")
    public ResponseEntity<Resource> downloadFile()
            throws Exception {
        Path path = Path.of("src/main/resources/file/sample_file_1.txt");
        Resource resource = new PathResource(path);
        return ResponseEntity.ok()
                .contentType(getContentType(path))
                .contentLength(resource.contentLength())
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }

    private MediaType getContentType(Path path) throws IOException {
        try {
            return MediaType.parseMediaType(Files.probeContentType(path));
        } catch (IOException e) {
            return MediaType.APPLICATION_OCTET_STREAM;
        }
    }
}

弥补

「HttpHeaders.CONTENT_DISPOSITION」是什么?

用于确定如何处理作为响应返回的文件的头文件信息。

ヘッダ内容処理内容inlineWEBページとして表示attachmentダウンロードするattachment; filename=”filename.jpg”ファイル名指定でダウンロードする
// WEBページとして表示
ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "inline");
// ダウンロードする
ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment")
// ファイル名指定でダウンロードする
ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")

“MediaType.APPLICATION_OCTET_STREAM是什么意思?”

• MIME的一种类型。
• 意指“不要在意文件类型!”的表达。

return MediaType.APPLICATION_OCTET_STREAM;

将二进制数据设置为响应(方法参数/HttpServletResponse)。

如果您希望在最后删除为下载而创建的临时文件时插入处理,请使用②而不是①。

请输入您要转换成汉语的原文或短语。

@Controller
@RequestMapping("/files")
public class SampleController {

    @Autowired
    FastExcel fastExcel;

    private final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    @GetMapping("/downloadFile2")
    public void downloadFile2(HttpServletResponse response) throws Exception {
        // テンプレートファイルをコピー → 一時ファイル作成
        Path templateFile = Path.of("src/main/resources/file/templateFile.txt");
        Path temporaryFile = Path.of("src/main/resources/tmp/" + format.format(new Date()) + ".txt");
        Files.copy(templateFile, temporaryFile);
        Resource resource = new PathResource(temporaryFile);
        // レスポンス作成
        response.setContentType(getContentType(temporaryFile).getType());
        response.setContentLengthLong(resource.contentLength());
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"");
        try (
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        ) {
            out.write(Files.readAllBytes(temporaryFile));
        }
        // 一時ファイル削除
        Files.deleteIfExists(temporaryFile);
    }

    private MediaType getContentType(Path path) throws IOException {
        try {
            return MediaType.parseMediaType(Files.probeContentType(path));
        } catch (IOException e) {
            return MediaType.APPLICATION_OCTET_STREAM;
        }
    }
}
广告
将在 10 秒后关闭
bannerAds