javascript结合fileReader 实现上传图片

关于File API这里就不详细解释了,小伙伴们自行度娘吧,来我们就要利用文件句柄来读取文件内容,这是通过FileReader来实现的,通过FileReader接口,我们可以异步地将文件内容加载到内存中,赋予某个js变量。

function getImgSrc(target, callback) {

    if (window.FileReader) {

        var oPreviewImg = null, oFReader = new window.FileReader();

        oFReader.onload = function (oFREvent) {

            oPreviewImg = new Image();

            var type = target.files[0].type.split("/")[1];

            var src = oFREvent.target.result;

            oPreviewImg.src = src;

            if (typeof callback == "function") {

                callback(oPreviewImg, target, type, src);

            }

            return oPreviewImg.src;

        };

        return (function () {

            var aFiles = target.files;

            if (aFiles.length === 0) {

                return;

            }

            if (!IsImgType(aFiles[0].type)) {

                alert("You must select a valid image file!");

                return;

            }

            if (aFiles[0].size > 1024 * 1024) {

                target.value = "";

                alert('Please upload image file size less than 1M.');

                return;

            }

            oFReader.readAsDataURL(aFiles[0]);

        })();

    }

    if (navigator.appName === "Microsoft Internet Explorer") {

        return (function () {

            document.getElementById("imagePreview").filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = target.value;

        })();

    }

}

以上是 javascript结合fileReader 实现上传图片 的全部内容, 来源链接: utcz.com/z/325982.html

回到顶部