Spring Boot文件下載

一、Spring Boot下載文件到本地硬碟

在Spring Boot中,我們可以通過以下代碼實現將一個文件下載到本地硬碟中:

@GetMapping("/download")
public ResponseEntity<FileSystemResource> download(HttpServletRequest request) throws IOException {
    String fileName = "file.txt";
    String filePath = "path/to/file/" + fileName;
    FileSystemResource fileSystemResource = new FileSystemResource(filePath);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Content-Disposition", "attachment; filename=" + fileName);
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");
    return ResponseEntity.ok().headers(headers).contentLength(fileSystemResource.contentLength())
        .contentType(MediaType.parseMediaType("application/octet-stream")).body(fileSystemResource);
}

我們可以從請求中得到文件名,然後通過FileSystemResource獲取文件的真實路徑。

使用ResponseEntity將文件的內容輸出到響應體中,實現文件下載到本地硬碟。同時通過添加相關的響應頭信息來告訴瀏覽器將這個響應當做一個文件下載。

二、Spring Boot FTP下載文件

如果要實現從FTP伺服器下載文件,我們可以使用Apache Commons Net庫

首先添加maven依賴:

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.6</version>
</dependency>

然後通過以下代碼實現從FTP伺服器下載文件:

@GetMapping("/ftpdownload")
public String ftpDownload(HttpServletRequest request) throws IOException {
    String server = "FTP伺服器地址";
    int port = 21;
    String user = "用戶名";
    String password = "密碼";
    String remoteFilePath = "遠程文件路徑";
    String localFilePath = "本地文件路徑";
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(server, port);
    ftpClient.login(user, password);
    InputStream inputStream = ftpClient.retrieveFileStream(remoteFilePath);
    OutputStream outputStream = new FileOutputStream(localFilePath);
    byte[] bytesArray = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(bytesArray)) != -1) {
        outputStream.write(bytesArray, 0, bytesRead);
    }
    boolean success = ftpClient.completePendingCommand();
    inputStream.close();
    outputStream.close();
    ftpClient.logout();
    ftpClient.disconnect();
    if (success) {
        return "下載成功";
    } else {
        return "下載失敗";
    }
}

使用FTPClient連接到FTP伺服器,並通過retrieveFileStream方法獲取文件的輸入流。

然後使用FileOutputStream將輸入流寫入到本地文件中。

三、Spring Boot文件上傳下載功能

我們可以通過Spring Boot的MultipartFile來實現文件的上傳,而下載則可以參考第一部分的做法。

以下代碼實現了文件上傳和下載的完整功能:

@GetMapping("/download")
public ResponseEntity<FileSystemResource> download(HttpServletRequest request) throws IOException {
    ...
}

@PostMapping("/upload")
public String upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
    String fileName = file.getOriginalFilename();
    String filePath = "path/to/file/" + fileName;
    file.transferTo(new File(filePath));
    return "上傳成功";
}

文件上傳使用@RequestParam註解獲取文件,然後通過transferTo方法將文件寫入到指定的路徑中。

文件下載使用和第一部分中的代碼一樣的方式。

四、Spring Boot瀏覽器下載文件

如果需要將文件直接顯示在瀏覽器中,而不是下載到本地硬碟,我們可以對第一部分中的代碼進行修改:

@GetMapping("/display")
public ResponseEntity<FileSystemResource> display(HttpServletRequest request) throws IOException {
    String fileName = "file.txt";
    String filePath = "path/to/file/" + fileName;
    FileSystemResource fileSystemResource = new FileSystemResource(filePath);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Content-Disposition", "inline; filename=" + fileName);
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");
    return ResponseEntity.ok().headers(headers).contentLength(fileSystemResource.contentLength())
        .contentType(MediaType.parseMediaType("application/octet-stream")).body(fileSystemResource);
}

將Content-Disposition響應頭的attachment改為inline即可直接在瀏覽器中顯示文件內容。

五、Spring Boot下載文件到本地目錄

如果需要將文件下載到指定的本地目錄中,我們可以通過以下代碼實現:

@GetMapping("/folder")
public void folder(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String fileName = "file.txt";
    String filePath = "path/to/file/" + fileName;
    File file = new File(filePath);
    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    response.setContentType("application/octet-stream");
    response.setContentLength((int) file.length());
    FileInputStream inputStream = new FileInputStream(file);
    OutputStream outputStream = response.getOutputStream();
    byte[] bytesArray = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(bytesArray)) != -1) {
        outputStream.write(bytesArray, 0, bytesRead);
    }
    inputStream.close();
    outputStream.close();
}

在這裡,我們使用HttpServletResponse的getOutputStream方法獲取輸出流,然後將文件的內容寫入到輸出流中。

六、Spring Boot批量下載文件

最後,如果需要實現批量下載文件的功能,可以通過以下代碼實現:

@GetMapping("/batch")
public void batch(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String[] fileNames = {"file1.txt", "file2.txt"};
    ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
    for (String fileName : fileNames) {
        String filePath = "path/to/file/" + fileName;
        File file = new File(filePath);
        FileInputStream inputStream = new FileInputStream(file);
        ZipEntry zipEntry = new ZipEntry(fileName);
        zipOut.putNextEntry(zipEntry);
        byte[] bytesArray = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(bytesArray)) != -1) {
            zipOut.write(bytesArray, 0, bytesRead);
        }
        inputStream.close();
    }
    zipOut.finish();
}

在這裡,我們首先將多個文件名存放在一個數組中,然後使用ZipOutputStream將這些文件壓縮為一個壓縮包。

在輸出響應體時,使用response的getOutputStream方法獲取輸出流並將壓縮包寫入到流中。

總結

本文詳細介紹了在Spring Boot中實現文件下載的多個方面,包括下載到本地硬碟中、從FTP伺服器下載文件、文件上傳下載功能、瀏覽器下載文件、下載文件到本地目錄和批量下載文件。

通過這些方法,我們可以實現非常靈活、實用的文件下載功能,便於我們在開發中實現各種各樣的需求。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/248504.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-12 13:27
下一篇 2024-12-12 13:27

相關推薦

發表回復

登錄後才能評論