How to preview the selected file title via Javascript?

Asked

Viewed 479 times

1

I have a code for image upload preview in Javascript. However I would like to use with document format, so that instead of showing the image that will be loaded, show only the name of the pdf/word file or an icon too.

Code I’ve already made:

function handleFileSelect() {
    //Check File API support
    if (window.File && window.FileList && window.FileReader) {

        var files = event.target.files; //FileList object
        var output = document.getElementById("result");

        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            //Only pics
            if (!file.type.match('image')) continue;

            var picReader = new FileReader();
            picReader.addEventListener("load", function (event) {
                var picFile = event.target;
                var div = document.createElement("div");
                div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" + "title='" + picFile.name + "'/>";
                output.insertBefore(div, null);
            });
            //Read the image
            picReader.readAsDataURL(file);
        }
    } else {
        console.log("Your browser does not support File API");
    }
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
<label for="files">Select multiple files:</label>
    <input id="files" type="file" multiple="multiple" />
    <output id="result" />

1 answer

2


Since you won’t be using images to see one preview of them, you can dispense with the API FileReader() and use the code below to take the file name and display an icon (if it is word or pdf):

function handleFileSelect() {
	var output = document.getElementById("result");
	arquivos = $("#files").prop("files");
	var nomes = $.map(arquivos, function(val) { return val.name; });
	for(x=0;x<nomes.length;x++){
		var extensao = nomes[x].split('.').pop().toLowerCase();
		var nome = nomes[x].substring(nomes[x].lastIndexOf("/"),nomes[x].length);
		var div = document.createElement("div");
		if(extensao == "doc" || extensao == "docx"){
			icone = "http://jonvilma.com/images/word-14.jpg";
		}else if(extensao == "pdf"){
			icone = "http://iconbug.com/data/5b/507/52ff0e80b07d28b590bbc4b30befde52.png";
		}else{
			icone = "https://orig01.deviantart.net/244d/f/2013/087/8/0/no_icon_by_slamiticon-d5z70lm.png";
		}
		div.innerHTML = "<img src='"+icone+"' height='24' /> "+nome;
		output.insertBefore(div, null);
	}
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="files">Select multiple files:</label>
    <input id="files" type="file" multiple="multiple" />
    <output id="result" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.