Cómo obtener el nombre del archivo cuando el usuario selecciona un archivo a través de?


He visto preguntas similares antes,que termina sin solución,por razones de seguridad.

Pero hoy veo que hostmonster ha implementado esto con éxito,cuando abro un ticket y adjunto un archivo en su backend.

Funciona tanto con firefox como con IE(versión 8 para ser exactos).

He verificado que es exactamente scripting del lado del cliente,no se envía ninguna solicitud(con firebug).

Ahora, ¿podemos reconsiderar esta pregunta?

Author: user198729, 2010-02-03

4 answers

Puede obtener el nombre de archivo , pero no puede obtener la ruta completa del sistema de archivos del cliente.

Intenta acceder al atributo value de tu archivo input en el evento change.

La mayoría de los navegadores le darán solo el nombre de archivo , pero hay excepciones como IE8 que le dará una ruta falsa como: "C:\fakepath\myfile.ext" y versiones anteriores ( IE ) que en realidad le dará la ruta completa del sistema de archivos del cliente (debido a su falta de seguridad).

document.getElementById('fileInput').onchange = function () {
  alert('Selected file: ' + this.value);
};
 85
Author: CMS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-03 04:33:02

Puedes usar el siguiente código:

JS

    function showname () {
      var name = document.getElementById('fileInput'); 
      alert('Selected file: ' + name.files.item(0).name);
      alert('Selected file: ' + name.files.item(0).size);
      alert('Selected file: ' + name.files.item(0).type);
    };

HTML

<body>
    <p>
        <input type="file" id="fileInput" multiple onchange="showname()"/>
    </p>    
</body>
 24
Author: Alex Paulino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-04 14:09:24

Acabo de probar haciendo esto y parece funcionar en firefox e IE

<html>
    <head>
        <script type="text/javascript">
            function alertFilename()
            {
                var thefile = document.getElementById('thefile');
                alert(thefile.value);
            }
        </script>
    </head>
    <body>
        <form>
            <input type="file" id="thefile" onchange="alertFilename()" />
            <input type="button" onclick="alertFilename()" value="alert" />
        </form>
    </body>
</html>
 9
Author: John Boker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-03 04:32:46

Voy a responder a esta pregunta a través de Javascript simple que es compatible con todos los navegadores que he probado hasta ahora (IE8 a IE11, Chrome, FF, etc.).

Aquí está el código.

function GetFileSizeNameAndType()
        {
        var fi = document.getElementById('file'); // GET THE FILE INPUT AS VARIABLE.

        var totalFileSize = 0;

        // VALIDATE OR CHECK IF ANY FILE IS SELECTED.
        if (fi.files.length > 0)
        {
            // RUN A LOOP TO CHECK EACH SELECTED FILE.
            for (var i = 0; i <= fi.files.length - 1; i++)
            {
                //ACCESS THE SIZE PROPERTY OF THE ITEM OBJECT IN FILES COLLECTION. IN THIS WAY ALSO GET OTHER PROPERTIES LIKE FILENAME AND FILETYPE
                var fsize = fi.files.item(i).size;
                totalFileSize = totalFileSize + fsize;
                document.getElementById('fp').innerHTML =
                document.getElementById('fp').innerHTML
                +
                '<br /> ' + 'File Name is <b>' + fi.files.item(i).name
                +
                '</b> and Size is <b>' + Math.round((fsize / 1024)) //DEFAULT SIZE IS IN BYTES SO WE DIVIDING BY 1024 TO CONVERT IT IN KB
                +
                '</b> KB and File Type is <b>' + fi.files.item(i).type + "</b>.";
            }
        }
        document.getElementById('divTotalSize').innerHTML = "Total File(s) Size is <b>" + Math.round(totalFileSize / 1024) + "</b> KB";
    }
    <p>
        <input type="file" id="file" multiple onchange="GetFileSizeNameAndType()" />
    </p>

    <div id="fp"></div>
    <p>
        <div id="divTotalSize"></div>
    </p>

*Tenga en cuenta que estamos mostrando el tamaño de archivo en KB (Kilobytes). Para conseguir en MB divídalo por 1024 * 1024 y así sucesivamente*.

Realizará salidas de archivo como estas al seleccionar Instantánea de una salida de muestra de este código

 1
Author: vibs2006,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-18 17:18:08