NodeJS undefined 不是一个对象(评估 'input.files[0])



当我尝试运行我的nextjs应用程序时,发生了以下错误。

TypeError: undefined is not an object (evaluating 'input.files[0]')

原因必须如下

validateAudioUpload(input){
var URL = window.URL || window.webkitURL;
var file = input.files[0];

if (file) {
var image = new Image();

image.onload = function() {
if (this.width) {
console.log('Image has width, I think it is real image');
//TODO: upload to backend
}
};

image.src = URL.createObjectURL(file);
}
}

在渲染返回部分我有

<Form.Group controlId="formFile" className="mb-3">
<Form.Label>Please select an Image File (500w x 500h)</Form.Label>
<Form.Control type="file" onChange={this.validateAudioUpload(this)}/>
</Form.Group>

现在,因为当页面加载时,它必须尝试运行onChange,并且它得到NULL,因为没有用户选择的文件。

我该如何解决这个问题?

在访问值之前添加一个简单的检查:

if (!input?.files || input.files.length === 0) return
var file = input.files[0];

试试这个

validateAudioUpload = (input) => {
var URL = window.URL || window.webkitURL;
var file = input.files[0];

if (file) {
var image = new Image();

image.onload = function() {
if (this.width) {
console.log('Image has width, I think it is real image');
//TODO: upload to backend
}
};

image.src = URL.createObjectURL(file);
}
}
<Form.Control type="file" onChange={this.validateAudioUpload}/>

最新更新