0

I'm trying to upload a file and convert that file to its data-uri counterpart without needing any sort of back-end, but I'm stuck at trying to figure out how to actually get the uploaded file.

document.getElementById("myInput").files[0]

allows me to access some information, but not the actual file. There's the file api, but I can't find much documentation about how to use it, just that it exists.

Is there any way to do this entirely in the browser?

Wychmire
  • 43
  • 3
  • `Blob.stream() Transforms the File into a ReadableStream that can be used to read the File contents` I think you're looking for this – CoderCharmander Jun 14 '20 at 19:44
  • Maybe this is what you were looking for https://stackoverflow.com/questions/36280818/how-to-convert-file-to-base64-in-javascript – Diyorbek Sadullaev Jun 14 '20 at 19:47
  • @DiyorbekSadullayev I believe it is (and is what I ended up using), how do I get this marked as a duplicate? – Wychmire Jun 18 '20 at 05:07

1 Answers1

0

Here's a code for multiple file input. You can do it for a single file by removing loop. This will take the file as soon as you select file and displays inside the selected img tag

HTML Code

<div>
    <img id="img-1" src="#" />
</div>
<div>
    <img id="img-2" src="#"/>
</div>

Javascript Code

function readURL(input) {
        if (input.files && input.files[0]) {
            var countFiles = input.files.length;
            for (var i = 0; i < countFiles; i++) {
                // console.log(input.files);
                if(i === 0) {
                    // console.log(input.files);
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        // console.log(e);
                        $('#img-1')
                            .attr('src', e.target.result)
                            .width(135)
                            .height(135);
                    };
                    reader.readAsDataURL(input.files[i]);
                }else if(i === 1) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        // console.log(e);
                        $('#img-2')
                            .attr('src', e.target.result)
                            .width(135)
                            .height(135);
                    };
                    reader.readAsDataURL(input.files[i]);
                }
            }
        }
    }