我需要帮助添加一些代码行来检查文件是图像,检查扩展名。这是我用来指示上传图像进度的代码。我在 php 中执行此操作,用户无法上传除 .jpg .jpeg .gif 和 .png 以外的任何文件,但他没有收到文件未上传的消息。当我为进度上传添加 javascript 代码时,我创建的 php 消息不再显示。
这是我的 javascript upload.js 文件代码:
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 扩展名并阻止其他扩展名。如果他试图上传其他类型的文件来提醒用户。