如果不是图像文件,请检查文件扩展名并提醒用户

时间:2013-04-14 18:00:18

标签: javascript image file-upload

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

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

3 个答案:

答案 0 :(得分:36)

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

答案 1 :(得分:1)

对于Vue.js

if (filename.match(/.(jpg|jpeg)$/i)){
                     $('#modalimage').modal('show')    
                     vm.downloadimage = result.data
                 }else{
                  const a = document.createElement('a')
                  a.setAttribute('href', result.data)
                  a.dispatchEvent(new MouseEvent("click", {'view': window, 'bubbles': 
true, 'cancelable': true}))
                 }

答案 2 :(得分:0)

你给类名-jsp

的样式
"Choose file",input:true,icon:true,classButton:"btn",classInput:"input-large name-jsp"

在你的jsp或html中你给id =&#34; cekJpg&#34;(点击上传文件不选择文件)

<input id="cekJpg" type="submit" class="btn btn-primary" value="Upload image"> 

在javascript

//if click button upload image with id="cekJpg"
$("#cekJpg").on('click', function (e) {
    //get your format file
    var nameImage = $(".name-jsp").val();
    //cek format name with jpg or jpeg
    if(nameImage.match(/jpg.*/)||nameImage.match(/jpeg.*/)){
        //if format is same run form
    }else{
        //if with e.preventDefault not run form
        e.preventDefault();
        //give alert format file is wrong
        window.alert("file format is not appropriate");
    }
});