Get a PNG file in the form of binary/octet-stream for download

https://i.sstatic.net/VFMbl.pngsteps to recreate the issue:

I have a Blob object that I am saving as form data through a service. The response I receive has a content-type of application/octet-stream, as shown in the attached image.

What result is expected?

  • To be able to download and view the application/octet-stream file as an image on my local machine using appropriate applications

What actually happens?

I can download the file as an image, but when I try to open it, I get an error message saying that the file format is not supported even though it is supposed to be an image with the .png extension.

function add() {
  $.ajax({
  url: 'https://localhost:3000/upload/sampleImage.png',
  type: 'GET',
  success: function (data) {
    const link = document.createElement('a');
    link.style.display = 'none';
    link.download = "sample image";
     link.href =  
       'data:' +
       'image/png' +
       ';base64,' +
       window.btoa(unescape(encodeURIComponent(data)));
    link.click();
  },
  error: function (request, error) {
    alert("Request: " + JSON.stringify(request));
  }
});

}

Any suggestions on how to successfully download and preview the file?

Answer №1

Make sure to set the responseType as blob in your request

If you are using HttpClient:

this.http.get("https://localhost:3000/upload/sampleImage.png",{responseType:'blob'}).subscribe((img)=>{
        const link = document.createElement('a');
        link.style.display = 'none';
        link.download = "sample image";
         link.href =window.URL.createObjectURL(data);
        link.click();
  });

If you prefer to use $.ajax (although not recommended), specify the dataType as blob and utilize window.URL.createObjectURL(data) to generate a URL

 $.ajax({
  url: 'https://localhost:3000/upload/sampleImage.png',
  type: 'GET',
  xhrFields:{
            responseType: 'blob'
        },
  success: function (data) {
    const link = document.createElement('a');
    link.style.display = 'none';
    link.download = "sample image";
    var blob = new Blob([data], {type: 'image/png'});
    link.href =window.URL.createObjectURL(blob);
    link.click();
  },
  error: function (request, error) {
    alert("Request: " + JSON.stringify(request));
  }

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

Troubleshooting: Unable to trigger click event on Vuejs component

Working with Vuejs and Vuikit components, I have set up the following structure: <template> <div class="uk-scope"> <vk-modal :show="isShow" v-if="config"> <vk-modal-close @click="alert('hello!')" large& ...

Unable to Display "Hello World" in Vue.js

I am attempting to launch the Vuejs hello world project on a Cloud 9 development environment. Despite its simplicity, I am unable to determine why it is not rendering, even though there are no visible errors. What could be the issue here? <!DOCTYPE h ...

Challenges with AJAX in Web Browsing

I'm encountering some strange issues with AJAX functionality not working consistently across different web browsers. Is there a specific requirement or workaround to ensure smooth operation across all browsers? The initial problem I am facing is that ...

Incorporating a file from a specific directory in AngularJS

Every time I execute /sites/all/themes/theme/js/controller.js $scope.template = 'partials/tpl.html' /sites/all/themes/theme/js/index.html <div ng-include='template'></div> /sites/all/themes/theme/js/partials/tpl.html & ...

Initiate the video and begin streaming with Angular 9

I've encountered an issue with a background video on my website where it sometimes doesn't automatically play when loaded. To address this, I implemented the following solution: <video #video autoplay muted loop id="video" *ngIf=&quo ...

Steps for integrating custom slot properties in MUI data grids

Custom pagination has been successfully implemented using the mui datagrid component. However, when attempting to pass props for pagination using datagrid's slotProps, an issue arises stating that the type of onChange does not match. How can this be c ...

Angular: Restarting a material reactive form

I am facing an issue with a form that includes one input from the material library. https://i.sstatic.net/zg0UL.png After submitting the form, I reset it in my submission method like this : onSubmitPriceForm() { // to do...... this.priceForm.r ...

Exploring ways to utilize Vue data variables and methods within the configuration options of Tabulator

Utilizing tabulator in conjunction with vue using the following packages: tabulator-tables and vue-tabulator. In an attempt to implement a click event on the tabulator row, I am faced with the challenge of accessing vue data variables within the scope of ...

Unspecified data populating my dynamically generated dropdown in JSON format

For the past day, I've been grappling with a seemingly simple issue that I just can't seem to crack. I have two dropdowns on my page - one for selecting a country and another for selecting a city. The idea is that when a user selects a country, t ...

Guide on adding markers using Google Maps API based on specific criteria

Hi there, I need assistance in developing the following requirements. In my database, there is parking lot information. Let's say each parking lot has two attributes: id and address. Via a spring controller, I am passing a list of parking lots t ...

Setting up personalized colors for logging in Angular 2 with ng2-logger

Recently, I decided to try out a new tool called ng2-logger to improve the visualization of my console logs. https://www.npmjs.com/package/ng2-logger However, I've noticed that the colors it generates are random. Is there a way for me to choose spec ...

The header row in HTML tables sometimes vanishes unexpectedly after sorting the table

Upon filtering the table, I noticed that the header disappears sporadically. The issue is that the table header row should remain in place regardless of whether or not the characters used for filtering are present in the table rows. In Example 1: When fil ...

Uh oh! The form submission has caused an error of type TypeError, stating that it is unable to read the property "

Upon submitting a form, the console displays this error: ERROR TypeError: Cannot read property 'text' of undefined The submit method is being passed to a component with an output decorator. Displayed below is the code : comments.component.t ...

Is submitting with JQuery always a hit or miss?

Hey there, I'm currently working on a problem and could use some help. I seem to be having trouble getting inside my function for form submission in JQuery. Despite setting up console.logs, it appears that my code never reaches the first function. Can ...

"Enhancing user experience with CSS hover effects on dynamically loaded content and mobile devices

I have developed a quiz with 2 answer options for each question. To prevent the questions from loading initially, visitors must click a start button, triggering the questions to load via Ajax. The issue I am facing is that when a question is answered, the ...

Obtaining the time taken for code execution in Typescript by capturing console.timeEnd() as

Can the value of console.timeEnd() be captured as a variable in Typescript? I need it for debugging but am unable to view console outputs while testing on my phone. If not, is there a simple alternative method to achieve this without relying on external G ...

The error handler function is missing in Zepto's $.post method

When I was using Zepto instead of jQuery, I noticed that while the $.ajax method has an error handler, other methods like $.post and $.get do not. Do you know why this is the case? Function Signature $.post(url, [data], function(data, status, xhr){ ... }, ...

Creating an xpath that utilizes an iFrame element sourced from jqueryui.com

Currently, I am exploring the https://jqueryui.com/selectmenu/ page in an attempt to create an xpath for the initial selector labeled as Select a speed. Though I have successfully built the xpath up to the iframe, I am unsure how to specifically access t ...

What is the process for sending data to a database using a URL?

I am in need of developing a public API for my application that will be capable of receiving a single POST request. The main goal is to provide users with the ability to submit data directly to my database without having to manually interact with forms on ...

Embedding JavaScript within an HTML document

Need help with linking HTML files and utilizing JavaScript outputs? I have an .html file displaying a webpage with tabs that I want to link to another .html file. How can I create a link on my page to navigate to the other file? Additionally, in the linked ...