valor subir ruta obtener nombre extension archivos archivo javascript

javascript - subir - obtener valor de un input file jquery



¿Cómo obtener el nombre del archivo desde una ruta completa usando JavaScript? (17)

¿De qué plataforma viene el camino? Las rutas de Windows son diferentes de POSIX, las rutas de Mac OS 9 son diferentes de RISC Las rutas de acceso son diferentes ...

Si es una aplicación web donde el nombre de archivo puede provenir de diferentes plataformas, no hay una solución. Sin embargo, un intento razonable es usar tanto ''/' (Windows) como ''/'' (Linux / Unix / Mac y también una alternativa en Windows) como separadores de ruta. Aquí hay una versión que no es RegExp para más diversión:

var leafname= pathname.split(''//').pop().split(''/'').pop();

¿Hay alguna forma de obtener el último valor (basado en el símbolo ''/') de una ruta completa?

Ejemplo:

C:/Documents and Settings/img/recycled log.jpg

Con este caso, solo quiero obtener recycled log.jpg de la ruta completa en JavaScript.


Ates, su solución no protege contra una cadena vacía como entrada. En ese caso, falla con TypeError: /([^(//|//|/:)]+)$/.exec(fullPath) has no properties .

Bobince, aquí hay una versión de nickf''s que maneja los delimitadores de ruta de DOS, POSIX y HFS (y cadenas vacías):

return fullPath.replace(/^.*(//|//|/:)/, '''');


En Node.js, puedes usar el módulo de análisis de Path ...

var path = require(''path''); var file = ''/home/user/dir/file.txt''; var filename = path.parse(file).base; //=> ''file.txt''


Guión exitoso para su pregunta, Prueba completa

<script src="~/Scripts/jquery-1.10.2.min.js"></script> <p title="text" id="FileNameShow" ></p> <input type="file" id="myfile" onchange="javascript:showSrc();" size="30">


<script type="text/javascript"> function replaceAll(txt, replace, with_this) { return txt.replace(new RegExp(replace, ''g''), with_this); } function showSrc() { document.getElementById("myframe").href = document.getElementById("myfile").value; var theexa = document.getElementById("myframe").href.replace("file:///", ""); var path = document.getElementById("myframe").href.replace("file:///", ""); var correctPath = replaceAll(path, "%20", " "); alert(correctPath); var filename = correctPath.replace(/^.*[////]/, '''') $("#FileNameShow").text(filename) }


La respuesta completa es:

<html> <head> <title>Testing File Upload Inputs</title> <script type="text/javascript"> function replaceAll(txt, replace, with_this) { return txt.replace(new RegExp(replace, ''g''),with_this); } function showSrc() { document.getElementById("myframe").href = document.getElementById("myfile").value; var theexa = document.getElementById("myframe").href.replace("file:///",""); var path = document.getElementById("myframe").href.replace("file:///",""); var correctPath = replaceAll(path,"%20"," "); alert(correctPath); } </script> </head> <body> <form method="get" action="#" > <input type="file" id="myfile" onChange="javascript:showSrc();" size="30"> <br> <a href="#" id="myframe"></a> </form> </body> </html>


La siguiente línea de código JavaScript le dará el nombre del archivo.

var z = location.pathname.substring(location.pathname.lastIndexOf(''/'')+1); alert(z);


No es más conciso que la answer de Nickf, pero esta "extrae" directamente la respuesta en lugar de reemplazar las partes no deseadas con una cadena vacía:

var filename = /([^//]+)$/.exec(fullPath)[1];


Poca función para incluir en su proyecto para determinar el nombre de archivo de una ruta completa para Windows, así como las rutas absolutas de GNU / Linux y UNIX.

/** * @param {String} path Absolute path * @return {String} File name * @todo argument type checking during runtime * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf * @example basename(''/home/johndoe/github/my-package/webpack.config.js'') // "webpack.config.js" * @example basename(''C://Users//johndoe//github//my-package//webpack.config.js'') // "webpack.config.js" */ function basename(path) { let separator = ''/'' const windowsSeparator = ''//' if (path.includes(windowsSeparator)) { separator = windowsSeparator } return path.slice(path.lastIndexOf(separator) + 1) }


Solo por el rendimiento, probé todas las respuestas dadas aquí:

var substringTest = function (str) { return str.substring(str.lastIndexOf(''/'')+1); } var replaceTest = function (str) { return str.replace(/^.*(//|//|/:)/, ''''); } var execTest = function (str) { return /([^//]+)$/.exec(str)[1]; } var splitTest = function (str) { return str.split(''//').pop().split(''/'').pop(); } substringTest took 0.09508600000000023ms replaceTest took 0.049203000000000004ms execTest took 0.04859899999999939ms splitTest took 0.02505500000000005ms

Y el ganador es la respuesta de estilo Split y Pop , ¡Gracias a Bobince !


Una pregunta que hace "obtener el nombre del archivo sin extensión" se refiere aquí, pero no hay solución para eso. Aquí está la solución modificada de la solución de Bobbie.

var name_without_ext = (file_name.split(''//').pop().split(''/'').pop().split(''.''))[0];


Yo suelo:

var lastPart = path.replace(///$/,'''').split(''//').pop();

Reemplaza al último / por lo que también funciona con carpetas.


var file_name = file_path.substring(file_path.lastIndexOf(''/''));


<html> <head> <title>Testing File Upload Inputs</title> <script type="text/javascript"> <!-- function showSrc() { document.getElementById("myframe").href = document.getElementById("myfile").value; var theexa = document.getElementById("myframe").href.replace("file:///",""); alert(document.getElementById("myframe").href.replace("file:///","")); } // --> </script> </head> <body> <form method="get" action="#" > <input type="file" id="myfile" onChange="javascript:showSrc();" size="30"> <br> <a href="#" id="myframe"></a> </form> </body> </html>


<script type="text/javascript"> function test() { var path = "C:/es/h221.txt"; var pos =path.lastIndexOf( path.charAt( path.indexOf(":")+1) ); alert("pos=" + pos ); var filename = path.substring( pos+1); alert( filename ); } </script> <form name="InputForm" action="page2.asp" method="post"> <P><input type="button" name="b1" value="test file button" onClick="test()"> </form>


<script type="text/javascript"> var path = ''<%=Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath %>''; </script>

Consulte de http://www.codeprojectdownload.com


function getFileName(path, isExtension){ var fullFileName, fileNameWithoutExtension; // replace / to / while( path.indexOf("//") !== -1 ){ path = path.replace("//", "/"); } fullFileName = path.split("/").pop(); return (isExtension) ? fullFileName : fullFileName.slice( 0, fullFileName.lastIndexOf(".") ); }


var filename = fullPath.replace(/^.*[////]/, '''')

Esto manejará ambos / OR / en rutas