How to preview the title of the selected file via Javascript?

1

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

Code I've already done:

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" />
    
asked by anonymous 08.09.2017 / 16:07

1 answer

2

Since you will not use images to see a preview of them, you can dispense with the FileReader() API and use the code below to get 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><labelfor="files">Select multiple files:</label>
    <input id="files" type="file" multiple="multiple" />
    <output id="result" />
    
09.09.2017 / 03:11