如何获取文件输入作为dataURI,然后将其存储在Javascript中的变量中?

问题描述 投票:0回答:1

所以我只是编写这个小应用程序,我有一个表单,提示用户输入图像,然后我需要将该图像作为 dataURI 并将该值存储在变量中以供以后使用。安迪想法如何做到这一点?

我尝试过 FileReader: readAsDataURL() 方法,但无法将其存储在变量中。我不是 JavaScript 天才,所以这可能是一个简单的修复,也可能是我的一个错误。

javascript html image data-uri
1个回答
0
投票

一个例子可能看起来像这样:

HTML:

<input type="file" id="imageInput" />

JS

document.getElementById('imageInput').addEventListener('change', function(event) {
    const file = event.target.files[0]; // Get the file
    const reader = new FileReader();

    reader.onloadend = function() {
        // This code runs once the FileReader has finished reading the file
        const dataURI = reader.result;
        console.log(dataURI); // You can see the Data URI in the console
        // Now you can store it in a variable for later use. For example:
        window.myAppImage = dataURI; // Storing it globally for demonstration; adjust as needed.
    };

    reader.readAsDataURL(file); // Read the file as Data URI
});
© www.soinside.com 2019 - 2024. All rights reserved.