2

I have example file paths on a web page like:

www.example.com/uploads/abc.pdf
www.example.com/uploads/abc.json
www.example.com/uploads/abc.txt
www.example.com/uploads/abc.avi

The file type can be anything. Some files are easily viewable in a browser like txt or image files but some file types start downloading when opened in a browser.

How can I know whether the URL file path is viewable in div or downloadable only? Is there any way to decide from the MIME type or anything we can check with Javascript/jQuery if that file is viewable in a div or downloadable only before viewing/downloading starts?

Any help would be appreciated.

1 Answer 1

1

Try with jQuery:

jQuery.get(url, function (response, status, xhr) {
  if (xhr.getResponseHeader("content-type").indexOf("text") > -1)
    // url content is of type : text
  else
    // url has downloadable content
});

For more intel, refer to : https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getResponseHeader

Sign up to request clarification or add additional context in comments.

3 Comments

Your answer is better but not complete solution. For lot of files like json or xml, it predict well. But pdf and image files are also viewable, and your solution will predict it as downloadable file. Pdf and Image files can be easily viewed on browser. Audio, video, csv and ms doc and lot more files get started downloaded and your solution is good for downloadable file. But for pdf and image file, your solution goes into else part.
Thanks @Ayoub EL ABOUSSI, it helps me to find solution.
You're welcome, then try defining an array to test against as you think its right in your case. happy coding.

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.