Home >Java >javaTutorial >How to implement file download function in Java Servlet?

How to implement file download function in Java Servlet?

王林
王林forward
2023-04-26 18:37:081665browse

1. Description

Servlet is a technology developed by Sun Corporation for interactively browsing and generating data and generating dynamic Web. Servlet in a narrow sense refers to an interface implemented by Java language. But generally, we call the Java program that implements the Servlet interface Servlet

2. Use the servlet program to download

//得到需要下载的文件
String path = this.getServletContext().getRealPath("/upload/9/1/图片1.png");
File file = new File(path);
//读取服务器本地的文件
FileInputStream in = new FileInputStream(file);
/**
 * 处理URL编码问题
 */
String fileName = file.getName();
//对文件名进行URl编码
fileName = URLEncoder.encode(fileName, "utf-8");
//判断不同浏览器
String userAgent = request.getHeader("user-agent");
String filefix = null;
if(userAgent.contains("Trident")){
//IE
filefix = "filename="+fileName;
}else if(userAgent.contains("Firefox")){
//Firefox
filefix = "filename*="+fileName;
}else{
filefix = "filename="+fileName;
}
//告诉浏览器以下载方式打开资源
response.setHeader("Content-Disposition", "attachment;"+filefix);
//把本地文件发送给浏览器
byte[] buf = new byte[1024];
int len = 0;
while( (len=in.read(buf))!=-1 ){
response.getOutputStream().write(buf, 0, len);
}
//关闭
in.close();

The above is the detailed content of How to implement file download function in Java Servlet?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete