Detailed Explanation of Servlet Program Download File Example in java

  • 2021-08-21 20:18:27
  • OfStack

For 1 common file download, presumably everyone will click on the default link for data acquisition. Slow efficiency is one aspect, and sometimes the download process is out of order. After learning some programs in python, we can choose to use Servlet to download files. Let's start with a brief explanation of Servlet, and then bring a code example of downloading files.

1. Description

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

2. Download using servlet program


// Get the files that need to be downloaded 
String path = this.getServletContext().getRealPath("/upload/9/1/ Picture 1.png");
File file = new File(path);
// Read files local to the server 
FileInputStream in = new FileInputStream(file);
/**
 *  Deal with URL Coding problem 
 */
String fileName = file.getName();
// For the file name URl Code 
fileName = URLEncoder.encode(fileName, "utf-8");
// Judge different browsers 
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;
}
// Tell the browser to open the resource for download 
response.setHeader("Content-Disposition", "attachment;"+filefix);
// Send local files to the browser 
byte[] buf = new byte[1024];
int len = 0;
while( (len=in.read(buf))!=-1 ){
response.getOutputStream().write(buf, 0, len);
}
// Shut down 
in.close();

Related articles: