温馨提示×

JAVA怎么返回文件流给前端

小亿
702
2024-02-29 14:57:17
栏目: 编程语言

在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路径时,就会弹出下载文件的对话框,用户可以选择保存文件或直接打开文件。

0