[英]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/test.com/car.jpeg
,而是基于令牌的图像,例如:
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
还有@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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.