Angular将文件输入转换为Base64

15

我正在尝试在我的Angular项目中将文件输入解析为base64。

在我的模板中,我有:

<input type="file" (change)="handleUpload($event)">

然后我的函数是这个:

handleUpload(event) {
    const file = event.target.files[0];
    const reader = new FileReader();
    reader.readAsDataURL(event);
    reader.onload = () => {
        console.log(reader.result);
    };
}

这让我出现了这个错误:

ERROR TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
    at _global.(anonymous function).(anonymous function) [as readAsDataURL] (webpack-internal:///./node_modules/zone.js/dist/zone.js:1323:60)
    at AccountFormComponent.handleUpload (account-form.component.ts:212)
    at Object.eval [as handleEvent] (AccountFormComponent.html:344)
    at handleEvent (core.js:13547)
    at callWithDebugContext (core.js:15056)
    at Object.debugHandleEvent [as handleEvent] (core.js:14643)
    at dispatchEvent (core.js:9962)
    at eval (core.js:10587)
    at HTMLInputElement.eval (platform-browser.js:2628)
    at ZoneDelegate.invokeTask (zone.js:421)

2
你正在将事件传递给方法而不是文件。 - Ricardo
我真是个笨蛋... - Sandra Willford
1个回答

47

你把事件传递给了方法而不是文件。

你的方法应该像这样:

handleUpload(event) {
    const file = event.target.files[0];
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
        console.log(reader.result);
    };
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接