用流写出文件到前端代码示例

import java.io.*;
 public class FileDownloadServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String filename = "hello.docx";
        String filepath = "/path/to/your/file/" + filename;
        File file = new File(filepath);
        String contentType = getServletContext().getMimeType(file.getAbsolutePath());
        response.setContentType(contentType);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        InputStream inputStream = new FileInputStream(file);
        OutputStream outputStream = response.getOutputStream();
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        inputStream.close();
        outputStream.close();
    }
}
posted @ 2023-06-18 01:16  ukyo--夜王  阅读(28)  评论(0编辑  收藏  举报