在Java中可以使用Servlet來返回文件流給前端。以下是一個簡單的示例代碼:
@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filePath = "/path/to/your/file.txt";
File file = new File(filePath);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
FileInputStream fileInputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
fileInputStream.close();
outputStream.close();
}
}
在上面的代碼中,我們首先指定了要下載的文件路徑,然后設置了響應的Content-Type和Content-Disposition頭信息,將文件流寫入到響應的輸出流中,最后關閉輸入輸出流。當瀏覽器請求/download路徑時,就會彈出下載文件的對話框,用戶可以選擇保存文件或直接打開文件。