一、基本使用方法
1、引入jQuery和fileupload.js文件
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="jquery.fileupload.js"></script>
2、創建上傳表單
<form id="fileupload" action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="file" multiple> <input type="submit" value="上傳"> </form>
3、綁定上傳事件
$('#fileupload').fileupload({ url: 'upload.php', // 後端處理上傳的地址 dataType: 'json', // 返回數據類型為json done: function (e, data) { // 上傳成功的回調函數 console.log(data.result); // 輸出上傳成功後的返回結果 }, fail: function (e, data) { // 上傳失敗的回調函數 console.log(data.errorThrown); } });
二、做出進度條
1、使用jQuery UI庫提供的進度條組件,需要引入jQuery UI庫的css和js文件
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
2、在綁定上傳事件的時候,添加代碼實現進度條
$('#fileupload').fileupload({ // 其他配置省略 progressall: function (e, data) { // 上傳進度變化時觸發的回調函數 var progress = parseInt(data.loaded / data.total * 100, 10); $('#progressbar').progressbar({value: progress}); // 更新進度條 } }); <div id="progressbar"></div>
三、解決跨域問題
1、在php文件中設置響應頭
header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
2、如果使用Apache作為Web伺服器,可以修改.htaccess文件
Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Methods "POST, GET, OPTIONS" Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"
四、解決上傳大文件時出現的問題
1、在php.ini文件中修改上傳文件的大小限制
upload_max_filesize = 100M post_max_size = 100M max_execution_time = 600
2、在Apache的httpd.conf文件中修改請求的響應時間
TimeOut 600
五、解決IE瀏覽器兼容性問題
1、在JS文件中添加以下代碼
// 解決IE瀏覽器中數據類型不匹配的問題 $.ajaxSetup({ xhrFields: { withCredentials: true // 解決IE瀏覽器的跨域問題 } }); // 解決IE瀏覽器文件上傳進度問題 $.support.cors = true;
2、在html文件中添加以下代碼
<!-- 解決IE瀏覽器中的跨域問題 --> <meta http-equiv="X-UA-Compatible" content="IE=edge">
原創文章,作者:UKRI,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/142872.html