gpt4 book ai didi

javascript - 检查文件扩展名,如果不是图像文件则提醒用户

转载 作者:可可西里 更新时间:2023-11-01 01:55:53 26 4
gpt4 key购买 nike

我需要帮助来添加一些代码来检查文件是否是图像,以检查扩展名。这是我用来指示上传图片进度的代码。我在 php 中这样做,用户不能上传任何文件,除了 .jpg .jpeg .gif 和 .png 但他没有收到文件未上传的消息。当我为进度上传添加 javascript 代码时,我创建的 php 消息不再显示。

这是我的javascriptupload.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 扩展名并阻止其他扩展名。提醒用户是否尝试上传其他类型的文件。

最佳答案

if (!fileInput.files[0].name.match(/\.(jpg|jpeg|png|gif)$/i))
alert('not an image');

关于javascript - 检查文件扩展名,如果不是图像文件则提醒用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16002412/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com