IT박스

Javascript-파일 입력 컨트롤에서 파일 이름을 추출하는 방법

itboxs 2020. 8. 6. 08:07
반응형

Javascript-파일 입력 컨트롤에서 파일 이름을 추출하는 방법


사용자가 웹 페이지에서 파일을 선택하면 파일 이름 만 추출 할 수 있기를 원합니다.

str.search 함수를 시도했지만 파일 이름이 c : \ uploads \ ilike.this.file.jpg 와 같은 경우 실패한 것 같습니다 .

확장자없이 파일 이름 만 추출하려면 어떻게해야합니까?


<input type = "file">업로드 ID가 있다고 가정하면 다음 과 같은 트릭을 수행해야합니다.

var fullPath = document.getElementById('upload').value;
if (fullPath) {
    var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
    var filename = fullPath.substring(startIndex);
    if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
        filename = filename.substring(1);
    }
    alert(filename);
}

문자열 ({filepath} / {filename})을 분할하고 파일 이름을 얻으려면 다음과 같이 사용할 수 있습니다.

str.split(/(\\|\/)/g).pop()

"pop 메서드는 배열에서 마지막 요소를 제거하고 해당 값을 호출자에게 반환합니다." 모질라 개발자 네트워크

예:

에서: "/home/user/file.txt".split(/(\\|\/)/g).pop()

당신은 얻는다 : "file.txt"


요즘 훨씬 간단한 방법이 있습니다.

var fileInput = document.getElementById('upload');   
var filename = fileInput.files[0].name;

매우 간단

let file = $("#fileupload")[0].files[0]; 
file.name

가정 :

<input type="file" name="file1" id="theFile">

JavaScript는 다음과 같습니다.

var fileName = document.getElementById('theFile').files[0].name;

var pieces = str.split('\\');
var filename = pieces[pieces.length-1];

방금이 버전을 만들었습니다. 내 기능을 사용하여 원하는 것을 추출 할 수 있습니다. 모두 필요하지 않으면 일부 코드를 쉽게 제거 할 수 있습니다.

<html>
<body>
<script type="text/javascript">
// Useful function to separate path name and extension from full path string
function pathToFile(str)
{
    var nOffset = Math.max(0, Math.max(str.lastIndexOf('\\'), str.lastIndexOf('/')));
    var eOffset = str.lastIndexOf('.');
    if(eOffset < 0 && eOffset < nOffset)
    {
        eOffset = str.length;
    }
    return {isDirectory: eOffset === str.length, // Optionally: && nOffset+1 === str.length if trailing slash means dir, and otherwise always file
            path: str.substring(0, nOffset),
            name: str.substring(nOffset > 0 ? nOffset + 1 : nOffset, eOffset),
            extension: str.substring(eOffset > 0 ? eOffset + 1 : eOffset, str.length)};
}

// Testing the function
var testcases = [
    "C:\\blabla\\blaeobuaeu\\testcase1.jpeg",
    "/tmp/blabla/testcase2.png",
    "testcase3.htm",
    "C:\\Testcase4", "/dir.with.dots/fileWithoutDots",
    "/dir.with.dots/another.dir/"
];
for(var i=0;i<testcases.length;i++)
{
    var file = pathToFile(testcases[i]);
    document.write("- " + (file.isDirectory ? "Directory" : "File") + " with name '" + file.name + "' has extension: '" + file.extension + "' is in directory: '" + file.path + "'<br />");
}
</script>
</body>
</html>

다음을 출력합니다 :

  • 이름이 'testcase1'인 파일의 확장자는 'jpeg'입니다. 'C : \ blabla \ blaeobuaeu'디렉토리에 있습니다.
  • 'testcase2'이름을 가진 파일의 확장자는 다음과 같습니다. 'png'는 '/ tmp / blabla'디렉토리에 있습니다.
  • 이름이 'testcase3'인 파일의 확장자는 'htm'이 (가) 디렉토리에 있습니다. ''
  • 이름이 'Testcase4'인 디렉토리의 확장자는 ''입니다. 디렉토리는 'C :'입니다.
  • 이름이 'fileWithoutDots'인 디렉토리의 확장자는 ''입니다. 디렉토리는 '/dir.with.dots'디렉토리에 있습니다.
  • 이름이 ''인 디렉토리의 확장자는 ''입니다. 디렉토리는 '/dir.with.dots/another.dir'디렉토리에 있습니다.

With && nOffset+1 === str.length added to isDirectory:

  • File with name 'testcase1' has extension: 'jpeg' is in directory: 'C:\blabla\blaeobuaeu'
  • File with name 'testcase2' has extension: 'png' is in directory: '/tmp/blabla'
  • File with name 'testcase3' has extension: 'htm' is in directory: ''
  • Directory with name 'Testcase4' has extension: '' is in directory: 'C:'
  • Directory with name 'fileWithoutDots' has extension: '' is in directory: '/dir.with.dots'
  • Directory with name '' has extension: '' is in directory: '/dir.with.dots/another.dir'

Given the testcases you can see this function works quite robustly compared to the other proposed methods here.

Note for newbies about the \\: \ is an escape character, for example \n means a newline and \t a tab. To make it possible to write \n, you must actually type \\n.


I assume you want to strip all extensions, i.e. /tmp/test/somefile.tar.gz to somefile.

Direct approach with regex:

var filename = filepath.match(/^.*?([^\\/.]*)[^\\/]*$/)[1];

Alternative approach with regex and array operation:

var filename = filepath.split(/[\\/]/g).pop().split('.')[0];

Input: C:\path\Filename.ext
Output: Filename

In HTML code, set the File onChange value like this...

<input type="file" name="formdata" id="formdata" onchange="setfilename(this.value)"/>

Assuming your textfield id is 'wpName'...

<input type="text" name="wpName" id="wpName">

JavaScript

<script>
  function setfilename(val)
  {
    filename = val.split('\\').pop().split('/').pop();
    filename = filename.substring(0, filename.lastIndexOf('.'));
    document.getElementById('wpName').value = filename;
  }
</script>

Neither of the highly upvoted answers actually provide "just the file name without extension" and the other solutions are way too much code for such a simple job.

I think this should be a one-liner to any JavaScript programmer. It's a very simple regular expression:

function basename(prevname) {
    return prevname.replace(/^(.*[/\\])?/, '').replace(/(\.[^.]*)$/, '');
}

First, strip anything up to the last slash, if present.

Then, strip anything after the last period, if present.

It's simple, it's robust, it implements exactly what's asked for. Am I missing something?


// HTML
<input type="file" onchange="getFileName(this)">

// JS
function getFileName(input) {
    console.log(input.files[0].name) // With extension
    console.log(input.files[0].name.replace(/\.[^/.]+$/, '')) // Without extension
}

How to remove the extension


None of the above answers worked for me, here is my solution which updates a disabled input with the filename:

<script type="text/javascript"> 
  document.getElementById('img_name').onchange = function () {
  var filePath = this.value;
    if (filePath) {
      var fileName = filePath.replace(/^.*?([^\\\/]*)$/, '$1');
      document.getElementById('img_name_input').value = fileName;
    }
  };
</script>

If you are using jQuery then

$("#fileupload").val();

참고URL : https://stackoverflow.com/questions/857618/javascript-how-to-extract-filename-from-a-file-input-control

반응형