我在MVC 5项目上工作,在那里我试图裁剪和验证图像的宽度和高度。
在这里jQuery代码,reader.readAsDataURL(this.files[0])发生错误‘无法读取属性'0’的未定义‘。
var imageCropWidth = 0;
    var imageCropHeight = 0;
    var cropPointX = 0;
    var cropPointY = 0;
 
    var _URL = window.URL || window.webkitURL;
    $('#files').change(function () {
        debugger
        var file, img;
        if ((file = this.files[0])) {
            img = new Image();
            img.onload = function () {
                if (this.width <= 200 && this.height <= 200) {
 
                    var reader = new FileReader();
 
                    reader.onload = function (e) {
                        // get loaded data and render thumbnail.
 
                        document.getElementById("image").src = e.target.result;
                        var jcrop_api = $('#image').Jcrop({
                            setSelect: [500, 500, 10, 10],
                            allowMove: true,
                            allowResize: false,
                            onChange: setCoordsAndImgSize,
                            boxWidth: 500,
                            boxHeight: 500
                            //onSelect: updatePreview
 
                        });
                        //jcrop_api.setOption({ allowMove: false });
                        //jcrop_api.setOption({ allowResize: false })
                    };
 
                    // read the image file as a data URL.
                    reader.readAsDataURL(this.files[0]);
                    loadPopup();
                }
                else {
 
                    //$("#txtfileTitle").attr("placeholder", "Upload Image");
                    var message = "Image should be maximum 200x200 pixel size.";
                    errormesssage(message);
                    return false;
 
                }
            };
            img.src = _URL.createObjectURL(file);
        }
    });
如何解决此错误?
而且,在裁剪之前或之后,这是验证图像宽度和高度的好方法吗?
发布于 2017-05-03 13:00:52
不能读取未定义的‘’的属性'0‘是因为您正在尝试访问数组'files’的元素'0‘,该数组为null或undefined。你应该首先确定为什么你正在使用的‘文件’没有被实例化,而你的代码期望它被实例化,并从那里开始工作。
尝试使用web浏览器中的web开发人员工具在if ((file = this.files[0]))行上放置一个断点,然后检查files未定义的原因。
一旦你通过了这一点,然后继续你的裁剪任务。您的代码:if (this.width <= 200 && this.height <= 200)可能是检查图像大小的有效方法,也可能不是。使用前面解释的here,尝试使用jQuery来获取对图像对象的引用。
祝好运!
发布于 2017-09-21 15:42:35
下面的错误:
this.files[0]您不能获取两次文件。在file变量中有files[0]。使用这个而不是那个。
reader.readAsDataURL(file);发布于 2020-02-26 20:45:19
我也遇到了同样的问题--我试图从数组中获取图像,结果得到了与您相同的消息。修复它的是,我将所有东西都包装在一个ng容器中,该容器首先检查信息是否已收到,如下所示:
<ng-container *ngIf="conceptCourse.Photos"> <!-- <- this removed the message in the console -->
    <img *ngIf="conceptCourse.Photos[1]['Path']" [src]="conceptCourse.Photos[1]['Path']"
         class="img-fluid z-depth-1"
         alt="{{conceptCourse.Photos[1]['Description']}}">
</ng-container>https://stackoverflow.com/questions/43751180
复制相似问题