Understanding how to retrieve the FileType from a Document Object Model using JavaScript

Looking at this DOM structure, we have an image with the following details:


<img id="this-is-the-image" src="http://192.168.1.100/Image_tmp/2016-06/d4eb8d">

The task at hand is to click a button, execute a JavaScript function, and download the image file.

The button implementation and the downloading script are already completed.

Below is a snippet of the code:

function downloadFile(fileName, url) {
        var aLink = document.createElement('a');
        var blob = new Blob([url]);
        var evt = document.createEvent("HTMLEvents");
        getImageType(blob);
        evt.initEvent("click", false, false);
        aLink.download = fileName;
        aLink.href = URL.createObjectURL(blob);
        aLink.dispatchEvent(evt);
    }

I've encountered an issue where I can only extract the source

"http://192.168.1.100/Image_tmp/2016-06/d4eb8d"
or the filename d4eb8d, while in reality, the image could be in the format of .png or .jpg. Although the browser displays it correctly, when saved, the file name defaults to just d4eb8d instead of including the extension like d4eb8d.png or d4eb8d.jpg. Is there a method to accurately determine the image type so that the downloaded file includes the correct extension?

Answer №1

If you need to retrieve an image file using JavaScript, you can utilize the XMLHttpRequest() function while setting the .responseType property to "blob". This will allow you to extract the image type from the blob using blob.type.split("/")[1], where type represents the MIME type of the Blob object. The result after splitting would typically be either jpg, jpeg, png, or another image format.

  window.onload = function() {
    var link = document.querySelector("a");
    var filename = "image";
    var req = new XMLHttpRequest();
    req.responseType = "blob";
    req.open("GET", "http://example.com/d4eb8d");
    req.onload = function() {
      var imgBlob = this.response;
      var imgType = imgBlob.type.split("/")[1];
      console.log(imgType);
      var event = document.createEvent("HTMLEvents");
      event.initEvent("click", false, false);
      link.download = filename + "." + imgType;
      link.href = URL.createObjectURL(imgBlob); 
      link.dispatchEvent(event);
    }
    req.send()
  }

See it in action on plnkr: http://plnkr.co/edit/To4uZXL8PUph9qG3azvZ?p=preview

Answer №2

Can we be certain that using new Blob([url]) will result in a blob containing image data, and not a text file with the content of

http://192.168.1.100/Image_tmp/2016-06/d4eb8d
?

It appears that converting an image link to a blob can only be achieved by reading it using XHR => How to get a file or blob from an object URL?

Once you have the blob, you can determine the file type by checking blob.type. Afterward, append the appropriate extension.

var ext ="";
switch(blob.type){
   case "image/jpeg":
        ext=".jpg";
        break;
   case "image/png":
        ext=".png";
        break;
   case "image/gif":
        ext=".gif";
        break;
}
aLink.download = fileName + ext;

Answer №3

When dealing with an instance of an HTMLImageElement, it seems that there is no built-in property in the documentation to determine its image type.

One approach could be to extract the URL, initiate an AJAX request to fetch the Content-Type header, which can help identify the file extension. However, this method relies on the remote server providing such information. Alternatively, you can utilize the XMLHttpRequest object and its .getResponseHeader() method.

Another solution involves changing the window.location to the image URL but keep in mind that downloading directly may not be possible without user interaction.

Finally, creating a simple server-side script to handle file downloads and processing details can also be an effective strategy.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to creating a versatile navigation bar using Bootstrap and HTML

I am looking to create a navigation menu that can be easily reused across multiple pages on my bootstrap/html website. Instead of duplicating code, I want to implement a solution for creating a reusable navigation menu in bootstrap/html. How can this be ...

Ways to identify whether a div is in view and includes an input field

This is a unique question that is not related to the issue of querySelectorAll detecting value in input. Instead of asking whether an input field has a value, I am interested in how to detect if the current visible div contains an input field. This is a n ...

Getting input elements with Puppeteer can be done by waiting for the page to fully load all elements within the frameset tag

Seeking to gather all input elements on this website: This is how the element source page appears. Below is my code snippet: const puppeteer = require("puppeteer"); function run() { return new Promise(async (resolve, reject) => { try { ...

Angular has the ability to round numbers to the nearest integer using a pipe

How do we round a number to the nearest dollar or integer? For example, rounding 2729999.61 would result in 2730000. Is there a method in Angular template that can achieve this using the number pipe? Such as using | number or | number : '1.2-2' ...

Unable to display the absolute path of the image src in WebStorm

Hey there! I recently started learning HTML5 and have been using WebStorm on my trusty Macbook Air for about two weeks now. I've encountered a problem with image sourcing that has left me puzzled. Here's my question: Why is it that images from ...

Retrieve the current element's 'this' object even after binding an external 'this' object

Is the title of this question confusing? Let's dive in. Imagine you have something like this: var Test = function(){ this.foo = a; } Test.prototype.init = function() { $(document).on('change', '.form-control', this.myFun ...

Ensuring the Line Breaks in CSS and JavaScript to Easily Modify the Style

Is there a way to determine when a line will break so I can apply different styles? The design team needs 3 buttons in a grid (3 columns) with specific sizes. They want buttons with content that breaks onto the next line to have a border-radius of 13px, w ...

Changing HTML dynamically does not trigger the ng-click event within ng-bind-html

I have developed a custom directive that can display messages along with rendering HTML content that may contain Angular attributes like buttons, anchor tags with ng-click attribute, and more. index.html: <ir-error-panel status="status"></ir-err ...

Stop the page from scrolling when scrolling within a specific DIV to address the [Violation] warning appearing in the console

Initially, it may seem like a duplicate question that has been answered here, but there are additional aspects that need to be addressed. How do I resolve the following [Violation] warning in the Google Chrome console? [Violation] Added non-passive eve ...

The initial render of children elements in React Google Maps Api may not display properly

I am struggling to incorporate the Google Maps API into my app. Everything works smoothly until I try to display a Marker at the initial rendering of the map. The Marker does not show up, but if I add another Marker after the rendering is complete, then it ...

Using regular expressions in JavaScript, we can separate a paragraph into individual sentences

Hey there! I'm currently working on a project that requires extracting sentences from a paragraph using regex in JavaScript. Unfortunately, my attempts to achieve this have resulted in syntax errors as I have tried methods used in other programming la ...

Having trouble importing a modified package forked for use in a Next.JS project

I've implemented react-headroom in my current project and had to modify its code so that the <header> wouldn't change height on different pages. To achieve this, I forked the original repository from here, made the necessary changes on my v ...

transferring information within React applications

I created a basic online store and I am looking to transfer data from one JavaScript file to another. The first JS file displays the items, and then I want to pass the item data to cart.js which contains a table. <section className="products"> ...

Steer clear of 405 errors by implementing AJAX in combination with Flask and JINJA templ

Hey there, I'm fairly new to backend work so please bear with me. I've been doing some research but haven't found the answer yet. Currently, I'm working on an application that fetches search results from a 3rd party API. I'm tryi ...

Reactjs Invariant Violation caused by the npm package (react-loader)

I'm currently attempting to integrate react-loader into my react component. This is the code snippet I'm using: /** @jsx React.DOM */ var Loader = require('react-loader'); var DisplayController = React.createClass({ // etc ...

The option value in mat-autocomplete is not displaying correctly on IOS devices

When I click on the first option in the dropdown menu, it does not display the selected option in the field. However, when I select the second option, then the value of the first option appears, and when I choose the third option, the value of the second o ...

Issue with JQuery UI Tabs not displaying additional HTML pages in JavaScript

One issue I'm facing is that I added Tabs from JQuery UI on my website. The tab containing paragraphs loads fine, but the tabs linked to other HTML pages (which don't have tabs) won't load. Here is my .js file code and .html code: $(funct ...

Adjusting the content within a text area using an AngularJS service

I am currently editing text in a textarea within the admin view and I would like to display it through an angular service on the user view. However, I want the text to be displayed in multiple rows, maintaining the same format that I entered in the textare ...

Do you have any recommendations for a creative CSS method to achieve a full-screen background image?

After searching online and experimenting with different methods, I have yet to discover a solution that suits my needs. My goal is to have the background image on my website centered, filling the entire browser screen, while also being compatible with resp ...

Retrieve a JSON object by making a request to a URL with specific parameters

Struggling with a common coder's mental block: The idea: Imagine entering a URL like www.mysite.com/getStuff?name=Jerry&occupation=Engineer&Id=12345 Rather than receiving a webpage, the goal is to get back a json object for parsing on anoth ...