简体   繁体   中英

Javascript - How to get the actual file from an input type=“file”

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?

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]);
                }
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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