programing

URL에서 파일 확장자를 가져올 수 있는 방법이 있습니까?

mailnote 2023. 5. 11. 21:41
반응형

URL에서 파일 확장자를 가져올 수 있는 방법이 있습니까?

제 스크립트에서 다운로드할 파일에 원하는 확장자가 있는지 확인하고 싶습니다.

파일은 다음과 같은 URL에 있지 않습니다.

http://example.com/this_url_will_download_a_file

또는 네, 하지만 저는 그런 종류의 URL만 사용할 것이라고 생각합니다.

http://example.com/file.jpg

다음과 같이 확인하지 않습니다.Url.Substring(Url.LastIndexOf(".") - 3, 3)왜냐하면 이것은 매우 형편없는 방법이기 때문입니다.

그래서, 당신은 나에게 무엇을 추천합니까?

이상하지만 효과가 있습니다.

string url = @"http://example.com/file.jpg";
string ext = System.IO.Path.GetExtension(url);
MessageBox.Show(this, ext);

그러나 아래 크로노가 언급한 것처럼 매개 변수에서는 작동하지 않습니다.

string url = @"http://example.com/file.jpg?par=x";
string ext = System.IO.Path.GetExtension(url);
MessageBox.Show(this, ext);

결과: ".jpg?par=x"

여기 제가 사용하는 간단한 것이 있습니다.매개 변수, 절대 및 상대 URL 등과 함께 작동합니다.

public static string GetFileExtensionFromUrl(string url)
{
    url = url.Split('?')[0];
    url = url.Split('/').Last();
    return url.Contains('.') ? url.Substring(url.LastIndexOf('.')) : "";
}

유닛 테스트를 수행할 경우

[TestMethod]
public void TestGetExt()
{
    Assert.IsTrue(Helpers.GetFileExtensionFromUrl("../wtf.js?x=wtf")==".js");
    Assert.IsTrue(Helpers.GetFileExtensionFromUrl("wtf.js")==".js");
    Assert.IsTrue(Helpers.GetFileExtensionFromUrl("http://www.com/wtf.js?wtf")==".js");
    Assert.IsTrue(Helpers.GetFileExtensionFromUrl("wtf") == "");
    Assert.IsTrue(Helpers.GetFileExtensionFromUrl("") == "");
}

필요에 따라 조정합니다.

추신: 사용 안 함Path.GetExtension쿼리 문자열 매개 변수와 함께 작동하지 않기 때문입니다.

저는 이것이 오래된 질문이라는 것을 알지만, 이 질문을 보는 사람들에게 도움이 될 수 있습니다.

URL 내의 파일 이름에서 확장자를 가져오는 가장 좋은 방법은 regex를 사용하는 것입니다.

다음 패턴을 사용할 수 있습니다(URL만 사용할 수 없음).

.+(\.\w{3})\?*.*

설명:

.+     Match any character between one and infinite
(...)  With this, you create a group, after you can use for getting string inside the brackets
\.     Match the character '.'
\w     Matches any word character equal to [a-zA-Z0-9_]
\?*    Match the character '?' between zero and infinite
.*     Match any character between zero and infinite

예:

http://example.com/file.png
http://example.com/file.png?foo=10

But if you have an URL like this:

http://example.com/asd
This take '.com' as extension.

따라서 다음과 같은 URL에 강력한 패턴을 사용할 수 있습니다.

.+\/{2}.+\/{1}.+(\.\w+)\?*.*

설명:

.+        Match any character between one and infinite
\/{2}     Match two '/' characters
.+        Match any character between one and infinite
\/{1}     Match one '/' character
.+        Match any character between one and infinite
(\.\w+)  Group and match '.' character and any word character equal to [a-zA-Z0-9_] from one to infinite
\?*       Match the character '?' between zero and infinite
.*        Match any character between zero and infinite

예:

http://example.com/file.png          (Match .png)
https://example.com/file.png?foo=10  (Match .png)
http://example.com/asd               (No match)
C:\Foo\file.png                      (No match, only urls!)

http://example.com/file.png

    http:        .+
    //           \/{2}
    example.com  .+
    /            \/{1}
    file         .+
    .png         (\.\w+)

만약 당신이 단지 그것을 얻고 싶다면..jpg의 일부http://example.com/file.jpg그럼 그냥 그녀의 가수가 제안하는 대로 사용하세요.

// The following evaluates to ".jpg"
Path.GetExtension("http://example.com/file.jpg")

다운로드 링크가 다음과 같은 경우http://example.com/this_url_will_download_a_file그러면 파일 이름이 "파일 저장" 대화상자를 표시하는 브라우저의 파일 이름을 제안하는 데 사용되는 HTTP 헤더인 Content-Disposition의 일부로 포함됩니다.이 파일 이름을 가져오려면 컨텐츠-Disposition 없이 파일 이름 가져오기에서 제안한 기술을 사용하여 다운로드를 시작하고 HTTP 헤더를 가져오지만 실제로 파일을 다운로드하지 않고 다운로드를 취소할 수 있습니다.

HttpWebResponse res = (HttpWebResponse)request.GetResponse();
using (Stream rstream = res.GetResponseStream())
{
    string fileName = res.Headers["Content-Disposition"] != null ?
        res.Headers["Content-Disposition"].Replace("attachment; filename=", "").Replace("\"", "") :
        res.Headers["Location"] != null ? Path.GetFileName(res.Headers["Location"]) : 
        Path.GetFileName(url).Contains('?') || Path.GetFileName(url).Contains('=') ?
        Path.GetFileName(res.ResponseUri.ToString()) : defaultFileName;
}
res.Close();

제 솔루션은 다음과 같습니다.

if (Uri.TryCreate(url, UriKind.Absolute, out var uri)){
    Console.WriteLine(Path.GetExtension(uri.LocalPath));
}

먼저 내 URL이 유효한 URL인지 확인한 다음 로컬 경로에서 파일 확장명을 가져옵니다.

일부에서는 URL에서 파일을 요청하고 헤더를 확인할 것을 제안했습니다.내 생각엔 단순한 것치고는 과잉 살상인 것 같아, 그래서...

URL에 매개 변수가 있으면 Heringer 응답이 실패합니다. 솔루션은 단순합니다.Split쿼리 문자열 char에?.

string url = @"http://example.com/file.jpg";
string ext = System.IO.Path.GetExtension(url.Split('?')[0]);

VirtualPathUtility.GetExtension(yourPath)선행 기간을 포함하여 지정된 경로에서 파일 확장명을 반환합니다.

언급URL : https://stackoverflow.com/questions/23228378/is-there-any-way-to-get-the-file-extension-from-a-url

반응형