前台代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
</head>
<body>
<h2>blob video demo</h2>
<video id="sound" width="500" height="300" controls="controls"></video>
<script type="text/javascript">
//创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
//配置请求方式、请求地址以及是否同步
xhr.open('POST', '/Today/VideoServlet', true);
//设置请求结果类型为blob
xhr.responseType = 'blob';
//请求成功回调函数
xhr.onload = function (e) {
if (this.status == 200) {//请求成功
//获取blob对象
var blob = this.response;
//获取blob对象地址,并把值赋给容器
document.getElementById('sound').src=URL.createObjectURL(blob);
}
};
xhr.send();
</script>
</body>
</html>
后台代码
package cn.com.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class VideoServlet extends HttpServlet {
/*
* author:命运的信徒
* arm:把.mp4结尾的视频转换为blob:http://加密的形式
*/
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//加载文件的位置
File file = new File("C:\\Users\\Administrator\\Desktop\\one\\1.mp4");
//获取文件名
String fileName = file.getName();
//判断浏览器的类型
String userAgent = req.getHeader("User-Agent").toLowerCase();
//如果是火狐浏览器的话,设置浏览器的编码格式
if (userAgent.indexOf("firefox") != -1) {
resp.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GB2312"), "ISO-8859-1"));
}
else {
resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
}
//设置response编码
resp.setCharacterEncoding("UTF-8");
resp.addHeader("Content-Length", "" + file.length());
//设置输出文件类型
resp.setContentType("video/mpeg4");
FileInputStream fis = null;
OutputStream os = null;
try {
//获取response输出流
os = resp.getOutputStream();
fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
// 输出文件
os.write(buffer,0,len);
}
} catch (Exception e) {
if (null != fis) {
fis.close();
}
if (null != os) {
os.flush();
os.close();
}
}
}
}
页面效果
![](https://i-blog.csdnimg.cn/blog_migrate/59138b3982976ee90b0b3445d567f01b.png)