简体   繁体   English

角度将文件输入转换为base64

[英]angular convert file input to base64

I am trying to parse a file input to base64 in my angular project.我正在尝试在我的角度项目中将文件输入解析为 base64。

In my template I have:在我的模板中,我有:

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

and then my function is this:然后我的功能是这样的:

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

which gives me this error:这给了我这个错误:

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)

you are passing the event to the method and not the file.您正在将事件传递给方法而不是文件。

your method should look like this:你的方法应该是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM