FileReader.Onload不能及时返回成功

FileReader.onload can not return successful in time

本文关键字:返回 成功 Onload 不能 FileReader      更新时间:2023-09-26

我想获得图像文件流并像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);
    }

以下是一些技巧

<-- 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)
    }
})

我已经解决了这个问题,只是把post request放到了onloaded函数中。

 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);
    }