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

How to implement file download function in Java Servlet?

王林
Release: 2023-04-26 18:37:08
forward
1673 people have browsed it

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();
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template