在上传文件之前使用Javascript显示图像和图像扩展的验证

时间:2014-01-28 03:28:28

标签: javascript image validation file-upload

我的目标是首先验证上传文件是图像,如果是图像,我会显示它。我从Validation CodeImage Code获取了代码。

起初我能够显示图像。但是,当我将显示图像代码与验证代码相结合时,我无法同时验证和显示工作。

任何人都可以帮助我吗?以下是我的代码。提前致谢! :)

<input type="file" name="dataFile" id="fileChooser" onchange="readURL(this);" />





<SCRIPT type="text/javascript">

var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];

     function readURL(input) {

         var arrInputs = document.getElementById("fileChooser").value;
            for (var i = 0; i < arrInputs.length; i++) {
                var oInput = arrInputs[i];
                if (oInput.type == "file") {
                    var sFileName = oInput.value;
                if (sFileName.length > 0) {
                    var blnValid = false;
                    for (var j = 0; j < _validFileExtensions.length; j++) {
                        var sCurExtension = _validFileExtensions[j];
                        if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                            blnValid = true;

                            if (input.files && input.files[0])  {
                                var reader = new FileReader();

                                reader.onload = function (e) {
                                    $('#blah').attr('src', e.target.result)
                                };

                                reader.readAsDataURL(input.files[0]);
                            }


                            break;
                        }
                    }

                    if (!blnValid) {
                        alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
                        return false;
                    }
                }
            }
        }

        return true;





    }

3 个答案:

答案 0 :(得分:15)

我能够解决它。下面是正确的代码。 :)

<强>的JavaScript

<SCRIPT type="text/javascript">
    function ValidateFileUpload() {
        var fuData = document.getElementById('fileChooser');
        var FileUploadPath = fuData.value;

//To check if user upload any file
        if (FileUploadPath == '') {
            alert("Please upload an image");

        } else {
            var Extension = FileUploadPath.substring(
                    FileUploadPath.lastIndexOf('.') + 1).toLowerCase();

//The file uploaded is an image

if (Extension == "gif" || Extension == "png" || Extension == "bmp"
                    || Extension == "jpeg" || Extension == "jpg") {

// To Display
                if (fuData.files && fuData.files[0]) {
                    var reader = new FileReader();

                    reader.onload = function(e) {
                        $('#blah').attr('src', e.target.result);
                    }

                    reader.readAsDataURL(fuData.files[0]);
                }

            } 

//The file upload is NOT an image
else {
                alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. ");

            }
        }
    }
</SCRIPT>

更改输入

<input type="file" name="dataFile" id="fileChooser" onchange="return ValidateFileUpload()" />

在上传之前显示图片

<img src="images/noimg.jpg" id="blah">

答案 1 :(得分:2)

我们解决了..这是完整的代码:)本代码将帮助您

  1. 上传并显示图片(不上传功能)
  2. 图片扩展验证
  3. 重置 img ,以防验证返回false
  4. function show(input) {
            debugger;
            var validExtensions = ['jpg','png','jpeg']; //array of valid extensions
            var fileName = input.files[0].name;
            var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
            if ($.inArray(fileNameExt, validExtensions) == -1) {
                input.type = ''
                input.type = 'file'
                $('#user_img').attr('src',"");
                alert("Only these file types are accepted : "+validExtensions.join(', '));
            }
            else
            {
            if (input.files && input.files[0]) {
                var filerdr = new FileReader();
                filerdr.onload = function (e) {
                    $('#user_img').attr('src', e.target.result);
                }
                filerdr.readAsDataURL(input.files[0]);
            }
            }
        }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <div class="form-group">
                  Upload Your Image
                        <div class="col-md-10">
                            <div>
                                <img id="user_img"
                                     height="130"
                                     width="130"
                                     style="border:solid" />
                            </div>
                            <div>
                                <input type="file" title="search image" id="file" name="file" onchange="show(this)" />
                            </div>
                        </div>
                    </div>

答案 2 :(得分:0)

function isValidPhoto(fileName)
{
    var allowed_extensions = new Array("jpg","png");
    var file_extension = fileName.split('.').pop().toLowerCase(); 

    for(var i = 0; i <= allowed_extensions.length; i++)
    {
        if(allowed_extensions[i] == file_extension)
        {
            return true; // valid file extension
        }
    }

    return false;
}