后台代码,仅需读取文件并变成二进制流:
/**
* bolb 测试
*/
public void getFile(HttpServletResponse response, HttpServletRequest request){File f = new File("service-web/src/main/resources/static/images/video1.mp4");String fileName = f.getName();String agent = request.getHeader("User-Agent").toUpperCase();InputStream fis = null;OutputStream os = null;try{fis = new BufferedInputStream(new FileInputStream(f.getPath()));byte[] buffer;buffer = new byte[fis.available()];fis.read(buffer);response.reset();//由于火狐和其他浏览器显示名称的方式不相同,需要进行不同的编码处理if(agent.indexOf("FIREFOX") != -1){//火狐浏览器response.addHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("GB2312"),"ISO-8859-1"));}else{//其他浏览器response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));}//设置response编码response.setCharacterEncoding("UTF-8");response.addHeader("Content-Length", ""+ f.length());//设置输出文件类型response.setContentType("video/mpeg4");//获取response输出流os = response.getOutputStream();// 输出文件os.write(buffer);}catch(Exception e){System.out.println(e.getMessage());} finally {//关闭流try {if (fis != null) {fis.close();}} catch (IOException e) {System.out.println(e.getMessage());} finally {try {if (os != null) {os.flush();}} catch (IOException e) {System.out.println(e.getMessage());} finally {try {if (os != null) {os.close();}} catch (IOException e) {System.out.println(e.getMessage());}}}}
}
前台接收代码:
function demoBlob() {//创建XMLHttpRequest对象var xhr = new XMLHttpRequest();//配置请求方式、请求地址以及是否同步xhr.open('POST', '/getBolb', true);//设置请求结果类型为blobxhr.responseType = 'blob';//请求成功回调函数xhr.onload = function (e) {if (this.status == 200) {//请求成功//获取blob对象var blob = this.response;//获取blob对象地址,并把值赋给容器console.log("!_______________________________________________________________________________________________")console.log("加密后的视频路径:"+URL.createObjectURL(blob));console.log("!_______________________________________________________________________________________________")}};xhr.send();
}