1

I fetch the file via fetch api.

I finally get something like this:

const result = response.blob()

currently, result.type returns image/jpeg. What I need to do is check if the file returned is a directory or image or text file.

One way is to do this:

if(result.type.includes('image')){

}

I am wondering if there's any other way without hardcoding image string like the above.

4
  • 1
    Are you looking for a method like blob.isImage or something? Commented Apr 7, 2021 at 11:28
  • Is this in a browser, i.e. you're looking for a constant or a mime type parser built-in to the fetch API or the browser? If it was node I'd guess there'd be other libraries you can load that would parse the string for you and give you simple properties to test, but that's probably not worth including otherwise. Commented Apr 7, 2021 at 11:28
  • blob.isImage would be great. blob.isDirectory would be great. some wrapper which makes it easier so i don't have to write hardcoded strings myself Commented Apr 7, 2021 at 11:30
  • yes, it's in a browser, but can use node too as i am using the webpack and react Commented Apr 7, 2021 at 11:32

1 Answer 1

2

mime types never change over time but will be extended, so it's not bad to hard code needed mime types, by the way you can check for image like below, for images it must start with "image":

result.type.startsWith("image/")

and for text:

result.type.startsWith("text/")

for other types, for example:

let others= ["video/mp4",...]
if(others.indexOf(result.type)>-1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.