用流写出文件到前端代码示例
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();
}
}
本文来自博客园,作者:ukyo--夜王,转载请注明原文链接:https://www.cnblogs.com/ukzq/p/17488608.html