如何强制浏览器下载文件?
2022-08-31 17:36:33
一切都很好,但只有当文件很小,大约1MB时,当我尝试使用更大的文件时,比如20MB我的浏览器显示它,而不是强制下载,到目前为止我尝试了许多标题,现在我的代码看起来:
PrintWriter out = response.getWriter();
String fileName = request.getParameter("filename");
File f= new File(fileName);
InputStream in = new FileInputStream(f);
BufferedInputStream bin = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bin);
while(din.available() > 0){
out.print(din.readLine());
out.print("\n");
}
response.setContentType("application/force-download");
response.setContentLength((int)f.length());
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Disposition","attachment; filename=\"" + "xxx\"");//fileName);
in.close();
bin.close();
din.close();