用jquery的ajax實現簡單的文件上傳功能,並且限制文件大小,先上代碼。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>test</title> <script src="https://cdn.bootcss.com/jquery/3.1.1/jquery.js"></script> </head> <body> <form id="uploadForm" enctype="multipart/form-data"> <input id="file" type="file" name="file"/> <button id="upload" type="button">上傳</button> </form> <script> var maxSize = 1000;//文件上傳大小限制 $('#upload').click(function(){ var size = document.getElementById('file').files[0].size; var filesize = (size / 1024).toFixed(2); if(filesize < maxSize){ $.ajax({ url: '/upload.php', type: 'POST', cache: false, data: new FormData($('#uploadForm')[0]), processData: false, contentType: false }).done(function(res) { alert('上傳文件成功'); }).fail(function(res) { alert('上傳文件失敗'); }); }else{ alert('上傳文件不許大於' + maxSize + 'KB'); } }); </script> </body> </html>
上傳是使用FormData對象來實現,利用files[0].size屬性來獲取文件的大小,進行上傳限制。