Java接口返回文件流保存本地

在Java开发中,有时候需要通过接口将文件流返回给前端,让用户可以下载文件。这时候,我们可以通过编写一个接口来实现文件流的返回,并在前端将文件保存到本地。

实现步骤

  1. 编写一个Controller接口,用来返回文件流给前端。
  2. 在接口中添加方法,将文件流返回给前端。
  3. 前端通过接口下载文件并保存到本地。

代码示例

Controller接口

@RestController
public class FileController {

    @GetMapping("/downloadFile")
    public ResponseEntity<Resource> downloadFile() {
        // 读取文件流
        Resource file = new FileSystemResource("path/to/file.pdf");

        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
                .body(file);
    }
}

前端代码

fetch('/downloadFile')
    .then(response => {
        return response.blob();
    })
    .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'file.pdf';
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
    });

关系图

erDiagram
    CUSTOMER ||--o| ORDER : places
    ORDER ||--| PRODUCT : includes
    ORDER ||--| PAYMENT : "makes payment"

旅行图

journey
    title My Journey
    section Getting Started
        Go to the store: 1 hour
        Buy supplies: 30 minutes
    section Travel
        Drive to the trailhead: 2 hours
        Hike to camp: 3 hours
    section Camp
        Set up tent: 30 minutes
        Cook dinner: 1 hour
    section Explore
        Hike to the summit: 2 hours
        Enjoy the view: 1 hour

通过以上代码示例,我们可以实现在Java中通过接口返回文件流,并在前端将文件保存到本地。这样就可以方便用户下载需要的文件。希望本篇文章对你有所帮助!