是的,Java的ResponseEntity可以返回文件流。你可以使用HttpHeaders
來設置響應頭,然后使用InputStreamResource
來包裝文件流,最后將InputStreamResource
作為參數傳遞給ResponseEntity
的構造函數。以下是一個簡單的示例:
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@RestController
public class FileDownloadController {
@GetMapping("/download")
public ResponseEntity<InputStreamResource> downloadFile(HttpServletRequest request) throws IOException {
// 設置文件路徑
String filePath = "/path/to/your/file.txt";
File file = new File(filePath);
// 檢查文件是否存在
if (!file.exists()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
// 設置響應頭
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));
// 創建文件輸入流
InputStream inputStream = new FileInputStream(file);
// 使用InputStreamResource包裝文件輸入流
InputStreamResource resource = new InputStreamResource(inputStream);
// 返回ResponseEntity
return ResponseEntity.status(HttpStatus.OK).headers(headers).body(resource);
}
}
在這個示例中,我們創建了一個名為FileDownloadController
的控制器,其中有一個名為downloadFile
的方法。這個方法接收一個HttpServletRequest
參數,用于獲取請求信息。我們首先設置文件路徑,然后檢查文件是否存在。接下來,我們設置響應頭,包括內容類型和內容處置表單數據。然后,我們創建一個文件輸入流,并使用InputStreamResource
將其包裝起來。最后,我們返回一個包含文件輸入流的ResponseEntity
對象。