php+ajax實現(xiàn)文件切割上傳功能示例
本文實例講述了php+ajax實現(xiàn)文件切割上傳功能。分享給大家供大家參考,具體如下:
html5中的File對象繼承Blob二進(jìn)制對象,Blob提供了一個slice函數(shù),可以用來切割文件數(shù)據(jù)。
<!DOCTYPE HTML><html lang='zh-CN'><head> <meta charset='UTF-8'> <title></title></head><body> <form method='post' id='myForm'> <input type='file' name='file' /> <input type='submit' name='submit' value='提交' /> </form> <div id='upStatus'></div></body><script type='text/javascript'> var myForm = document.getElementById('myForm'); var upfile = document.getElementById('upfile'); myForm.onsubmit = function() { //獲取文件對象 var file = upfile.files[0]; //獲取文件大小 var fileSize = file.size; //一次截取的大小(字節(jié)) var CutSize = 1024 * 1024 * 10; //開始截取位置 var CutStart = 0; //結(jié)束截取位置 var CutEnd = CutStart + CutSize; //截取的臨時文件 var tmpfile = new Blob(); while(CutStart < fileSize) { tmpfile = file.slice(CutStart, CutEnd); //我們創(chuàng)建一個FormData對象 var fd = new FormData(); //把文件添加到FormData對象中 fd.append('file', tmpfile); var xhr = new XMLHttpRequest(); //這里使用同步 xhr.open('post', 'upfile.php', false); //上傳進(jìn)度 console.log(Math.round( (CutStart + tmpfile.size) / fileSize * 100) + '%'); //發(fā)送FormData對象 xhr.send(fd); //重新設(shè)置截取文件位置 CutStart = CutEnd; CutEnd = CutStart + CutSize; } return false; };</script></html>
upfile.php代碼如下:
<?php$uploadDir = ’./upload/’;if(!file_exists($uploadDir)) { @mkdir($uploadDir, 0777, true);}$uploadFile = $uploadDir . basename($_FILES[’file’][’name’]);if(!file_exists($uploadFile)) { //如果文件不存在 move_uploaded_file($_FILES[’file’][’tmp_name’], $uploadFile);} else { //如果文件已存在,追加數(shù)據(jù) file_put_contents($uploadFile, file_get_contents($_FILES[’file’][’tmp_name’]), FILE_APPEND);}
更多關(guān)于PHP相關(guān)內(nèi)容可查看本站專題:《PHP+ajax技巧與應(yīng)用小結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
相關(guān)文章:
1. python中scrapy處理項目數(shù)據(jù)的實例分析2. 快速搭建Spring Boot+MyBatis的項目IDEA(附源碼下載)3. js抽獎轉(zhuǎn)盤實現(xiàn)方法分析4. IntelliJ IDEA導(dǎo)入jar包的方法5. Python requests庫參數(shù)提交的注意事項總結(jié)6. GIT相關(guān)-IDEA/ECLIPSE工具配置的教程詳解7. 教你在 IntelliJ IDEA 中使用 VIM插件的詳細(xì)教程8. python dict如何定義9. 如何基于Python實現(xiàn)word文檔重新排版10. vue-electron中修改表格內(nèi)容并修改樣式
