FileReader.onload无法及时返回成功

时间:2016-09-10 06:20:41

标签: javascript jquery

我想获取图像文件流并将它们传递给背景,如asp.net,但每次我尝试触发onload事件时,它总是在编程通过后完成。

我尝试使用setTimeout来阻止它并让它处理并等待它成功,但它失败了。 下面的评论解释了我失败了哪一步。谢谢。

 $("#goodsImage").change(function (e) {
        if ($("#goodsImage").val() == "")
        {
            alert("please choose the image you want to upload");
            return;
        }

        var filepath = $("#goodsImage").val();

        //$("#goodsImage").val();
        var extStart=filepath.lastIndexOf(".");
        var ext=filepath.substring(extStart,filepath.length).toUpperCase();
        if(ext!=".BMP"&&ext!=".PNG"&&ext!=".GIF"&&ext!=".JPG"&&ext!=".JPEG"){
            alert("only images could be uploaded");
            return;
        }
        readFile(e.target.files[0]);
        setTimeout(function () {
            //I want to use setTimeOut to delay it
        }, 1000);


       //always undefined!!!
       if ($("#hidImageStream").val() != "")
       {
           $.post("@Url.Action("UploadGoodImage")", { localPath: readerRs }, function (e)
           {
               if (e) {
                   $("#ImagePreviewUrl").val(e.data);
               }
               else {

               }
           });
       }



    });

    function readFile(file) {
        var reader = new FileReader();
        reader.onload = readSuccess;

        //always success after post request accomplished.
        function readSuccess(evt) {

            document.getElementById("hidImageStream").
                value = evt.target.result;

        };
        reader.readAsText(file);
    }

2 个答案:

答案 0 :(得分:2)

这里有一些提示

<-- use accept and only allow image mimetype. It can accept extension to -->
<input type="file" name="pic" accept="image/*">
  • 另外,将文件读作readAsText对于二进制文件来说是一个可怕的想法。 (所有我看到你改为base64)。
  • readAsDataURL不是因为上传量大3倍,需要更多的CPU /内存。
  • 欺骗文件名很容易,所以最好是实际测试它是否是图像


$("#goodsImage").change(function() {
    // We use `this` to access the DOM element instead of target
    for (let file of this.files) {
        // Test if it's a image instead of looking at the filename
        let img = new image
        img.onload = () => {
            // Success it's a image
            // upload file
            let fd = new FormData
            fd.append('file', file)

            $.ajax({
                url: 'http://example.com',
                data: fd,
                processData: false, // so jquery can handle FormData
                type: 'POST',
                success: function( data ) {
                    alert( data )
                }
            })
        }

        img.onerror = () => {
            // only images dude
        }

        img.src = URL.createObjectURL(file)
    }
})

答案 1 :(得分:0)

我已经解决了这个问题,只需将post请求放入onloaded funciton。

 function readFile(file) {
        var reader = new FileReader();
        reader.onloadend = readSuccess;
        //reader.onloadend = function (e) {
        //    console.log(e.target.result);
        //};

        function readSuccess(evt) {
            $.post("@Url.Action("UploadGoodImage")", { localPath: evt.target.result}, function (e) {
            if (e.IsSuccess) {
                $("#ImagePreviewUrl").val(e.data);
            }
            else {
                alert("Fail!");
            }

        });
        }
        reader.readAsDataURL(file);
    }