1

Given a URL like http://www.....jpg, how can I get the MIME type in Angular? e.g. image, audio, or video?

I understand that the MIME type can be found with file uploads as was explained here.

Bentaye
  • 9,403
  • 5
  • 32
  • 45
Michael Riess
  • 25
  • 2
  • 7

1 Answers1

1

In order to answer this question I will have to make a few assumptions:

Assumptions:

  1. http://www.....jpg could be located on any server, not only yours
  2. You have server access to implement part of the solution server side.

Problem 1: Cross Origin Requests

Imagine this scenario:

Your angular app is hosted on www.myserver.com. Someone visit your site, loads and runs your angular code in their browser. Now you want their browser to investigate the mime type of www.someimage.com/1.jpg. Loading that file would be a Cross-Origin request which is not allowed by default. If you have access to both servers you can allow this type of request by implementing Cross-Origin Resource Sharing for certain URIs, but that's not going to help you.

Problem 2: HTTP Content Negotiation

HTTP implements content negotiation for URIs. This wikipedia article explains it well. This is important here because:

A resource may be available in several different representations; for example, it might be available in different languages or different media types.

Possible solution:

Although you will not be able to check for MIME types for an arbitrary URI using client-side (angular) code, you can still solve this by implementing a small http service on your server. The flow would be something like this:

  1. Your angular application pass the URI in a post request to your server
  2. Your server examines the URI, and makes a HTTP connection to the server hosting the resource. How to do this will depend on what type of web server you are running.
  3. After figuring out the MIME type your server responds to the initial request with the MIME types. Note: plural. As the URI might be avaliable in many different formats.
jjabba
  • 494
  • 3
  • 16
  • Thanks for the detailed explanation. I'm trying to just do everything client side, but I'll probably end up doing something like you suggested. I understand how following any arbitrary url would be an issue. Do you have to actually follow the url to get the MIME type or could it simply be done by looking at the file extension? – Michael Riess May 22 '18 at 15:29
  • The MIME type will be provided with the actual resource by the webserver as part of the request for the resource. Thus you cannot "get" it without requesting the resource. If you want to make educated guesses what the MIME type *might be* based of the resource link or filename you can. But there is no guarantees that it will be accurate. – jjabba May 23 '18 at 16:37