这边用一个简单的servlet实现java从服务端下载文件的操作
写一个servlet:
<servlet>
<servlet-name>DownloadServlet</servlet-name>
<servlet-class>DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownloadServlet</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
java代码:
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream; public class DownloadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String filePath = "D:\\360MoveData\\Users\\123\\Desktop\\WebComponents.exe";
String fileName = "WebComponents.exe";
String fileType = "application/octet-stream"; //设置文件的类型
response.setContentType(fileType);
// 确保弹出下载对话框
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
FileInputStream inputStream = new FileInputStream(filePath);
//输出流
OutputStream outputStream = response.getOutputStream();
byte[] bytes = new byte[4096];
int length;
while ((length = inputStream.read(bytes)) > 0){
outputStream.write(bytes, 0, length);
}
inputStream.close();
outputStream.flush();
} public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
doGet(request, response);
}
}