本文介绍Web开发中文件下载功能的实现。后端通过Java设置Content-Disposition为attachment并输出流,前端提供Form提交、动态插入iframe以及window.open三种请求方式,浏览器识别响应头后触发保存对话框。
文件下载功能概述
在Web开发过程中,实现文件下载功能十分常见,以下提供一个基础示例。
Java后端实现逻辑
服务器端基于Java语言进行开发:
@RequestMapping(value = "download.html", method = RequestMethod.GET)
public void download(String resourceid, HttpServletRequest request, HttpServletResponse response) {
response.setContentType("charset=UTF-8");
File file = new File(path);
response.setHeader("Content-Disposition", "attachment; filename=a");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
OutputStream fos = null;
InputStream fis = null;
try {
fis = new FileInputStream(file.getAbsolutePath());
bis = new BufferedInputStream(fis);
fos = response.getOutputStream();
bos = new BufferedOutputStream(fos);
int bytesRead = 0;
byte[] buffer = new byte[5 * 1024];
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
}catch(E e){
}finally {
try {
bis.close();
bos.close();
fos.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
当前端发起该地址请求时,服务器首先定位目标文件,配置响应头信息,随后通过输出流将数据发送至浏览器。
浏览器解析响应头后,识别出主体为文件流,从而自动弹出“另存为”对话框,提示用户保存文件。
实现下载的关键在于Content-Disposition响应头,它是MIME协议的扩展,用于指示客户端如何处理附件内容。
该属性支持两种取值:
inline,表示在浏览器内在线打开文件。
attachment,表示作为附件进行下载。
本例中将其设置为attachment,因此浏览器会将其识别为附件并触发下载流程。
前端请求下载的三种方式
上述内容介绍了服务器端的实现逻辑,接下来讲解前端如何发起请求。
前端发起下载请求主要有三种方式:
1. Form表单提交
<form action='download.html' method='post'>
<input type='submit'/>
</form>
2. iframe嵌入
var iframe = "<iframe style='display:none' src='download.html'></iframe>"
body.append(iframe);
当将iframe元素动态添加到body中时,会自动触发对下载链接的请求。
3. window.open方法
window.open("download.html");