简体   繁体   中英

How to retrieve image name from url in javascript?

In my case, it's not straight forward like SomeDomain/test.com/car.jpeg but instead it's a token based image like:

SomeDomain/upload/document/ciOiJIUzUxMiJ9.eyJmaWxlX2lkiZXhwIjoxNjEwNjQ4MDY2fQ.e4doztYLOl6FTafUc7bJXrzwb-4FgaXTkJkk8S9GC4gsZhMVRh?subscription-key=f2721f4fa0a2f

I can retrieve this in a browser. I can even see the name of the image on the browser tab.

If you are trying to get the actual url, just use this:

let url = window.location.href; 
/* 
>> "http://somedomain/upload/document/ciOiJIUzUxMiJ9.eyJmaWxlX2lkiZXhwIjoxNjEwNjQ4MDY2fQ.e4doztYLOl6FTafUc7bJXrzwb-4FgaXTkJkk8S9GC4gsZhMVRh?subscription-key=f2721f4fa0a2f"
*/

If you are trying to get the path, use this:

let path = window.location.pathname; 
/*
>> "/upload/document/ciOiJIUzUxMiJ9.eyJmaWxlX2lkiZXhwIjoxNjEwNjQ4MDY2fQ.e4doztYLOl6FTafUc7bJXrzwb-4FgaXTkJkk8S9GC4gsZhMVRh"
*/

And if you want to get the name after the last slash, use this:

let path = window.location.pathname;
let nameAfterLastSlash = path.substring(path.lastIndexOf('/'), path.length);
/*
>> "/ciOiJIUzUxMiJ9.eyJmaWxlX2lkiZXhwIjoxNjEwNjQ4MDY2fQ.e4doztYLOl6FTafUc7bJXrzwb-4FgaXTkJkk8S9GC4gsZhMVRh"
/*

I just got this solution and its working. And also as suggested by @kyle

getFileName(filePath) {
    let fileName = null;
    const xhr = new XMLHttpRequest();
    xhr.open("GET", filePath, false);
    xhr.send();
    if (xhr.status==200) {
      const contentDisposition = xhr.getResponseHeader('Content-Disposition');
      fileName = contentDisposition.split(';')[1].split('filename')[1].split('=')[1].split('.')[0].trim();
    }
    return fileName;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM