我需要帮忙添加一行代码来检查是文件是图像,检查扩展名.这是我的代码,用于表示上传图像的进度.我在PHP中执行此操作,用户无法上传除.jpg .jpeg .gif和.png之外的任何文件,但他没有收到该文件未上传的消息.当我添加进度上传的
JavaScript代码时,我创建的PHP消息taht不再显示.
var handleUpload = function(event) { event.preventDefault(); event.stopPropagation(); var fileInput = document.getElementById('image_id'); var data = new FormData(); data.append('javascript',true); if(fileInput.files[0].size > 1050000) { document.getElementById("image_id").innerHTML = "Image too big (max 1Mb)"; alert('Fotografija koju želite dodati je veća od 1Mb!'); window.location="upload_images.PHP" return false; } for (var i =0; i < fileInput.files.length; ++i) { data.append('image',fileInput.files[i]); } var request = new XMLHttpRequest(); request.upload.addEventListener('progress',function(event) { if (event.lengthComputable) { var percent = event.loaded / event.total; var progress = document.getElementById('upload_progress'); while (progress.hasChildNodes()) { progress.removeChild(progress.firstChild); } progress.appendChild(document.createTextNode(Math.round(percent * 100) + ' %')); } }); request.upload.addEventListener('load',function(event) { document.getElementById('upload_progress').style.display = 'none'; }); request.upload.addEventListener('error',function(event) { alert('Dodavanje slika nije bilo uspješno! Pokušajte ponovo.'); }); request.addEventListener('readystatechange',function(event) { if (this.readyState == 4) { if(this.status == 200) { var links = document.getElementById('uploaded'); window.location="upload_images.PHP?success" console.log(this.response); } else { console.log('Server replied with HTTP status ' + this.status); } } }); request.open('POST','upload_images.PHP'); request.setRequestHeader('Cache-Control','no-cache'); document.getElementById('upload_progress').style.display = 'block'; request.send(data); } window.addEventListener('load',function(event) { var submit = document.getElementById('submit'); submit.addEventListener('click',handleUpload); });
<div id="uploaded"> </div> <div> <form action="" method="post" enctype="multipart/form-data"> <input name="image" id="image_id" type="file" size="25" value="Odaberi sliku" /> <input type="submit" id="submit" value="Dodaj Foto"/> </form> </div> <div class="upload_progress" id="upload_progress"></div>
我需要在那个javascript代码中检查是文件是图像.允许jpg,jpeg,png和gif扩展名并阻止其他的.提醒用户他是否尝试上传其他类型的文件.
解决方法
if (!fileInput.files[0].name.match(/.(jpg|jpeg|png|gif)$/i)) alert('not an image');