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

Show off a sleek slider within a Bootstrap dropdown menu

Is there a way to display a sleek slider within a Bootstrap dropdown element? The issue arises when the slider fails to function if the dropdown is not open from the start, and the prev/next buttons do not respond correctly. For reference, here is my curr ...

Incorporate fresh Google sites into different web pages using iFrame integration

Wishing you a fantastic day! I am currently working on embedding a brand new Google site into another webpage. I attempted to use an iframe for this purpose, but unfortunately it did not work as expected. Here is the code snippet: <iframe width="1280 ...

Do I have to additionally check the data type using typeof when implementing PropTypes in my code?

I have a custom method called onNotifyChange that is triggered in the onChange event of an input element. This method has been defined with a PropType of func. MyComponent.propTypes = { onNotifyChange: PropTypes.func, } When invoking the onNotifyCha ...

The synergy between ES6 arrow functions and array mapping techniques

I'm currently exploring shorthand methods of writing ES6 code and I've come across an example that has left me puzzled. The last shorthand used, "({length})", retrieves the length property of an array. While I understand how it works in this cont ...

The phantom stdout for Node 4.2.0 is showing an error with code NETWORK_ERR: XMLHttpRequest Exception 101. This error indicates that a network error

Executing the code below in node 4.2.0, it is triggered within a scheduled node cron job rather than through the terminal. The website being 'requested' is . module.exports.dynamicRequest = function(url, callback) { var makeDynamicRequest = fu ...

Using JSON to insert an array into an object with identical key name

var arr = ['1', '2', '3'] var part = {} var partContents = [] arr.map(function(i){ partContents.push({ obj: i }) part['text'] = partContents }) console.log(part); Is there a way to create separate arrays with ...

Utilize the _sortBy function from the lodash library to arrange an array based on a specific field

Looking at an array of objects similar to this: myArray = [ {AType: "aaa", Description: "De", …}, {AType: "bbb", Description: "Hi", …}, {AType: "ccc", Description: "Un", …}, {AType: "ddd", Description: ...

Having trouble with data retrieval from MySQL using PHP and Angular on certain mobile devices, although it functions properly on desktops and laptops

The data retrieved from the mysql database is functioning properly on desktop and laptop, but not on mobile devices. The following HTML code is present in the html file: <table class="table table-default"> <thead> <tr> & ...

What is the process for incorporating synchronous tasks within an asynchronous function?

const fs = require('fs') const readline = require('readline') const stream = require('stream') const rl = readline.createInterface({ input: fs.createReadStream('logs.txt') }) var uniqueItems = new Set() // ASY ...

Could you display the picture prior to the function commencing?

This is the image that needs to be loaded before the loop begins. <div id="attendenceGridDivLoader" style="display:none"> <img src="<?php echo base_url() . 'images/loader.gif'; ?>" /> </div> <select onchange=checkAll ...

Chrome debugging tool does not refresh page source

This issue has been lingering for quite some time and despite similar questions, I have not come across a satisfactory solution. The problem lies in the fact that the SOURCE used to step through the code does not refresh with every page load. Disabling the ...

What could be causing the issue with HTML not being printed upon button click in ReactJS?

My goal is to display the word "Hello" on the screen when the add button is clicked. However, I am encountering an issue where it is not showing up. Any insights or solutions would be greatly appreciated! import React, { Component } from 'react'; ...

Tips for managing the number of items returned in a dataProvider using AS3

*Hey there! I'm looking to only display 100 items in a list component from a dataProvider, even if it contains more than 500 or even 1000 items. Specifically, I want the first 100 items with cameras on to be included, and then fill the rest to reach a ...

The user interface does not get refreshed right away; it only shows the changes after the

Here is an example of HTML: <div ng-repeat="user in controller.users"> <p>{{user.name}}</p> <button ng-click="controller.deleteUser(user)" value="delete"></button> </div> Next, we have the controller code: vm ...

Caution: The React Hook useEffect is missing a required dependency

What is the best way to eliminate the warning "React Hook useEffect has a missing dependency" while developing my code? Here is a snippet of the code that triggers the warning: useEffect(() => { if(inactive){ document.querySelect ...

Reduce and combine JavaScript files without the need for Grunt or Gulp

My project involves working with over 50 JavaScript files that I want to combine and compress to optimize file size and minimize HTTP requests. The catch is, the client's system does not have Node or npm installed. How can I accomplish this task witho ...

Issue: The error message "undefined variable 'angular'" appears when attempting to access offline files stored on a network drive

I have successfully developed offline forms using angular js v1.6.4, angular-ui-bootstrap, and angular-ui-router without the need for server hosting. When the package is saved on local storage, it functions perfectly on both IE and Chrome browsers. Howeve ...

Getting a specific piece of information from a JSON file

I am encountering an issue with my JSON file collection. When I access it through http://localhost:5000/product/, I can see the contents without any problem. However, when I try to retrieve a specific product using a link like http://localhost:5000/product ...

"Repeating SignalR Messages: Issue of Duplication when Stopping and Restarting

Whenever I stop and start the connection, messages sent to the client by the hub are duplicated. If I follow this sequence: $.connection.hub.stop() $.connection.hub.start() {...} and a message is sent from the server hub to the client, it is initially re ...

Setting `tabBarVisible` to false does not function properly within a stackNavigation nested element

Details on my project dependencies: "react-navigation": "^3.6.0", "expo": "^32.0.0" I'm working with a TabNavigator that contains redirections to child components, which are StackNavigators. However, I'm facing an issue where I am unable to hide ...