实现Java SpringBoot文件下载

作为一名经验丰富的开发者,你需要教导一名刚入行的小白如何实现Java SpringBoot文件下载。接下来,我将为你详细介绍整个实现过程,包括步骤、代码示例和解释。

流程

首先,我们来看整个实现文件下载的流程:

步骤 操作
1 用户点击下载按钮
2 后端接收下载请求
3 后端读取文件
4 后端返回文件给前端

代码示例

1. 后端接收下载请求

@RestController
public class FileDownloadController {

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

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

2. 前端发送下载请求

function downloadFile() {
    fetch('/downloadFile')
    .then(response => {
        return response.blob();
    })
    .then(blob => {
        const url = window.URL.createObjectURL(new Blob([blob]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'file.txt');
        document.body.appendChild(link);
        link.click();
        link.parentNode.removeChild(link);
    });
}

流程图

sequenceDiagram
    participant User
    participant Frontend
    participant Backend

    User->>Frontend: 点击下载按钮
    Frontend->>Backend: 发送下载请求
    Backend->>Backend: 读取文件
    Backend-->>Frontend: 返回文件
    Frontend-->>User: 下载文件

通过以上步骤和代码示例,你应该可以很快地学会如何在Java SpringBoot中实现文件下载。祝你顺利!