在浏览器中异步下载文件,其实就是把服务器响应的文件先保存在内存中。然后再一次下载到磁盘。第二次下载过程,就是把内存的数据IO到磁盘,没有网络开销。速度极快。
之所以要先保存在内存,主要是可以在下载开始之前和下载结束后可以做一些业务逻辑(例如:校验,判断),还可以监听下载的进度。
演示
这里演示一个Demo,在点击下载摁钮后,弹出加loading
框。在读取到服务器的响应的文件后。关闭loading
框。并且在控制台中输出下载的进度。
有点像是监听文件下载完毕的意思,也只能是
像
。从内存IO到磁盘的这个过程,JS代码,再也无法染指过程。更谈不上监听了。
Controller
服务端的下载实现
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/download")
public class DownloadController {
@GetMapping
public void download (HttpServletRequest request,
HttpServletResponse response,
@RequestParam("file") String file) throws IOException {
Path path = Paths.get(file);
if (Files.notExists(path) || Files.isDirectory(path)) {
// 文件不存在,或者它是一个目录
response.setStatus(HttpServletResponse