切片上传/视频

//cs页面

<!DOCTYPE html>  

<html>  
    <head>  
        <meta charset="UTF-8"/>  
        <title>xhr2</title>  
    </head>  
    <body>  
        <div  id="drop_area" style="border:3px dashed silver;width:200px; height:200px">  
            将图片拖拽到此  
        </div>  
          
        <progress value="0" max="10" id="prouploadfile"></progress>  
          
        <span id="persent">0%</span>  
        <br />  
        <!--<button οnclick="xhr2()">ajax上传</button>-->     
        <button οnclick="stopup()" id="stop">上传</button>      
        <script>  
        //拖拽上传开始  
        //-1.禁止浏览器打开文件行为  
        document.addEventListener("drop",function(e){  //拖离   
            e.preventDefault();      
        })  
        document.addEventListener("dragleave",function(e){  //拖后放   
            e.preventDefault();      
        })  
        document.addEventListener("dragenter",function(e){  //拖进  
            e.preventDefault();      
        })  
        document.addEventListener("dragover",function(e){  //拖来拖去    
            e.preventDefault();      
        })  
        //上传进度  
        var pro = document.getElementById('prouploadfile');  
        var persent = document.getElementById('persent');  
        function clearpro(){  
            pro.value=0;  
            persent.innerHTML="0%";  
        }  
          
        //2.拖拽  
        var stopbutton = document.getElementById('stop');  
          
        var resultfile=""  
        var box = document.getElementById('drop_area'); //拖拽区域     
        box.addEventListener("drop",function(e){           
            var fileList = e.dataTransfer.files; //获取文件对象    
            console.log(fileList)  
            //检测是否是拖拽文件到页面的操作            
            if(fileList.length == 0){                
                return false;            
            }             
            //拖拉图片到浏览器,可以实现预览功能    
            //规定视频格式  
            //in_array  
            Array.prototype.S=String.fromCharCode(2);  
            Array.prototype.in_array=function(e){  
                var r=new RegExp(this.S+e+this.S);  
                return (r.test(this.S+this.join(this.S)+this.S));  
            };  
            var video_type=["video/mp4","video/ogg"];  
              
            //创建一个url连接,供src属性引用  
            var fileurl = window.URL.createObjectURL(fileList[0]);                
            if(fileList[0].type.indexOf('image') === 0){  //如果是图片  
                var str="<img width='200px' height='200px' src='"+fileurl+"'>";  
                document.getElementById('drop_area').innerHTML=str;                   
            }else if(video_type.in_array(fileList[0].type)){   //如果是规定格式内的视频                    
                var str="<video width='200px' height='200px' controls='controls' src='"+fileurl+"'></video>";  
                document.getElementById('drop_area').innerHTML=str;        
            }else{ //其他格式,输出文件名  
                //alert("不预览");  
                var str="文件名字:"+fileList[0].name;  
                document.getElementById('drop_area').innerHTML=str;      
            }         
            resultfile = fileList[0];     
            console.log(resultfile);      
              
            //切片计算  
            filesize= resultfile.size;  
            setsize=500*1024;  
            filecount = filesize/setsize;  
            //console.log(filecount)  
            //定义进度条  
            pro.max=parseInt(Math.ceil(filecount));   
              
              
              
            i =getCookie(resultfile.name);  
            i = (i!=null && i!="")?parseInt(i):0  
              
            if(Math.floor(filecount)<i){  
                alert("已经完成");  
                pro.value=i+1;  
                persent.innerHTML="100%";  
              
            }else{  
                alert(i);  
                pro.value=i;  
                p=parseInt(i)*100/Math.ceil(filecount)  
                persent.innerHTML=parseInt(p)+"%";  
            }  
              
        },false);    
          
        //3.ajax上传  
  
        var stop=1;  
        function xhr2(){  
            if(stop==1){  
                return false;  
            }  
            if(resultfile==""){  
                alert("请选择文件")  
                return false;  
            }  
            i=getCookie(resultfile.name);  
            console.log(i)  
            i = (i!=null && i!="")?parseInt(i):0  
              
            if(Math.floor(filecount)<parseInt(i)){  
                alert("已经完成");  
                return false;  
            }else{  
                //alert(i)  
            }  
            var xhr = new XMLHttpRequest();//第一步  
            //新建一个FormData对象  
            var formData = new FormData(); //++++++++++  
            //追加文件数据
            //改变进度条  
            pro.value=i+1;  
            p=parseInt(i+1)*100/Math.ceil(filecount)  
            persent.innerHTML=parseInt(p)+"%";  
            //进度条  
              
              
            if((filesize-i*setsize)>setsize){  
                blobfile= resultfile.slice(i*setsize,(i+1)*setsize);  
            }else{  
                blobfile= resultfile.slice(i*setsize,filesize);  
                formData.append('lastone', Math.floor(filecount));  
            }  
                formData.append('file', blobfile);  
                //return false;  
                formData.append('blobname', i); //++++++++++  
            formData.append('filename', resultfile.name); //++++++++++  
                //post方式  
                xhr.open('POST', 'xhr2.php'); //第二步骤  
                //发送请求  
                xhr.send(formData);  //第三步骤  
                stopbutton.innerHTML = "暂停"  
                //ajax返回  
                xhr.onreadystatechange = function(){ //第四步  
                if ( xhr.readyState == 4 && xhr.status == 200 ) {  
                  console.log( xhr.responseText );  
                        if(i<filecount){  
                            xhr2();  
                        }else{  
                            i=0;
                        }  
                }  
              };  
                //设置超时时间  
                xhr.timeout = 20000;  
                xhr.ontimeout = function(event){  
                alert('请求超时,网络拥堵!低于25K/s');  
              }           
                  
                i=i+1;  
                setCookie(resultfile.name,i,365)  
                  
        }  
          
        //设置cookie  
        function setCookie(c_name,value,expiredays)  
        {  
            var exdate=new Date()  
            exdate.setDate(exdate.getDate()+expiredays)  
            document.cookie=c_name+ "=" +escape(value)+  
            ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()+";path=/")  
        }  
        //获取cookie  
        function getCookie(c_name)  
        {  
        if (document.cookie.length>0)  
          {  
          c_start=document.cookie.indexOf(c_name + "=")  
          if (c_start!=-1)  
            {   
            c_start=c_start + c_name.length+1   
            c_end=document.cookie.indexOf(";",c_start)  
            if (c_end==-1) c_end=document.cookie.length  
            return unescape(document.cookie.substring(c_start,c_end))  
            }   
          }  
        return ""  
        }  
          
          
        function stopup(){  
            if(stop==1){  
                stop = 0  
                  
                xhr2();  
            }else{  
                stop = 1  
                stopbutton.innerHTML = "继续"  
                  
            }  
              
        }  
        </script>  
    </body>  

</html>  

xhr2.php

//后台页面

<?php  
//$name=$_POST['username'];  
$dir=$_POST['filename'];  
$dir="uploads/".md5($dir);  
file_exists($dir) or mkdir($dir,0777,true);  
  
  
$path=$dir."/".$_POST['blobname'];  
  
  
//print_r($_FILES["file"]);  
move_uploaded_file($_FILES["file"]["tmp_name"],$path);  
  
if(isset($_POST['lastone'])){  
    echo $_POST['lastone'];  
    $count=$_POST['lastone'];  
      
    $fp   = fopen($_POST['filename'],"abw");  
    for($i=0;$i<=$count;$i++){  
        $handle = fopen($dir."/".$i,"rb");    
        fwrite($fp,fread($handle,filesize($dir."/".$i)));    
        fclose($handle);      
    }  
    fclose($fp);  
}    
?>


在 Spring Boot 中实现切片上传视频,需要进行以下步骤: 1. 前端切片上传:前端将视频文件进行切片,使用 Form Data 将切片文件上传到后端。可以使用 axios 或者 jQuery 的 ajax 进行文件上传。 2. 后端接收切片文件:后端接收前端上传切片文件,可以使用 Spring Boot 的 MultipartFile 类型接收文件流。 3. 后端合并切片文件:将接收到的切片文件进行合并,生成完整的视频文件。可以使用 RandomAccessFile 类型进行文件合并。 4. 前端进度条展示:前端可以通过监听上传事件,实时展示上传进度条。 5. 后端断点续传:可以为切片上传添加断点续传功能,保证上传的可靠性和完整性。 示例代码如下: 前端代码: ```javascript // 切片上传 function uploadFile() { var file = document.getElementById("file").files[0]; var chunkSize = 1024 * 1024; // 切片大小,这里设置为 1MB var chunks = Math.ceil(file.size / chunkSize); // 切片总数 var currentChunk = 0; // 当前切片编号 var fileReader = new FileReader(); var formData = new FormData(); var xhr = new XMLHttpRequest(); xhr.open("POST", "/video/upload", true); fileReader.onload = function (e) { formData.append("file", new Blob([e.target.result])); formData.append("name", file.name); formData.append("chunks", chunks); formData.append("currentChunk", currentChunk); formData.append("chunkSize", chunkSize); xhr.upload.onprogress = function (event) { if (event.lengthComputable) { var complete = (event.loaded / event.total * 100 | 0); console.log("complete:" + complete + "%"); } }; xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); currentChunk++; if (currentChunk < chunks) { fileReader.readAsArrayBuffer(file.slice(currentChunk * chunkSize, (currentChunk + 1) * chunkSize)); } else { console.log("上传完成"); } } }; xhr.send(formData); }; fileReader.readAsArrayBuffer(file.slice(0, chunkSize)); } ``` 后端代码: ```java @RestController @RequestMapping("/video") public class VideoController { private static final String UPLOAD_DIR = "upload/"; @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file, @RequestParam("name") String name, @RequestParam("chunks") int chunks, @RequestParam("currentChunk") int currentChunk, @RequestParam("chunkSize") int chunkSize) { try { File dir = new File(UPLOAD_DIR); if (!dir.exists()) { dir.mkdirs(); } File chunkFile = new File(UPLOAD_DIR + name + "_" + currentChunk); IOUtils.copy(file.getInputStream(), new FileOutputStream(chunkFile)); if (currentChunk == chunks - 1) { File targetFile = new File(UPLOAD_DIR + name); FileOutputStream outputStream = new FileOutputStream(targetFile, true); for (int i = 0; i < chunks; i++) { File tempFile = new File(UPLOAD_DIR + name + "_" + i); FileInputStream inputStream = new FileInputStream(tempFile); byte[] buffer = new byte[(int) tempFile.length()]; inputStream.read(buffer); outputStream.write(buffer); inputStream.close(); tempFile.delete(); } outputStream.close(); } return "success"; } catch (IOException e) { e.printStackTrace(); return "error"; } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值