代码之家  ›  专栏  ›  技术社区  ›  Sandra Willford

角度将文件输入转换为base64

  •  10
  • Sandra Willford  · 技术社区  · 8 年前

    我正在尝试分析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)
    
    1 回复  |  直到 8 年前
        1
  •  32
  •   Ricardo    6 年前

    您正在将事件传递给方法,而不是文件。

    您的方法应如下所示:

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