Vue: downloading a file straight to your browser with the download attribute

I'm having an issue with axios where I am trying to download both a PDF and an image file. The image file downloads successfully and opens without any problems, but when I attempt to open the PDF file, it doesn't work as expected.

downloadItem({ url, name }) {
      axios
        .get(url, { responseType: 'blob' })
        .then((response) => {
          const blob = new Blob([response.data], { type: response.data.type });
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = name;
          link.click();
          URL.revokeObjectURL(link.href);
        })
        .catch(console.error);
    },

Can anyone provide some assistance on this matter? Apologies for any language errors in my writing.

Answer №1

Is this solution suitable for your needs?

axios
.get(url, {
  headers: {
    'Accept': 'application/pdf'
  },
  responseType: 'blob' })
.then(function (response) {
  switch ([WHAT IS YOUR DESIRED FILE TYPE]) {
    case "image": {
      const blob = new Blob([response.data], { type: response.data.type });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = name;
      link.click();
      URL.revokeObjectURL(link.href);
      break
    }
    case "pdf": {
      const blob = new Blob([response.data], { type: 'application/pdf' })
      const objectUrl = window.URL.createObjectURL(blob)
      window.open(objectUrl)
      elt.impressionEnCours = false
      break
    }
  }
})
.catch(function (error) {
  console.log(JSON.stringify(error))
})

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

I am searching for a way to apply a conditional class to the chosen element in react, as the toggle method does not

I'm working on customizing a dropdown menu and I want to add a functionality where if a parent li menu has an arrow class before the ul element, then clicking on that parent li menu will add a class called showMenu only to that specific sub-menu. Her ...

js simulate a click on an anchor element based on the child element's id

I am trying to automatically trigger a click on an a tag that contains a div with the id='a'. $(document).ready(function() { $("#chat_list_content a:has(div[id='a'])").click(); //$("#chat_list_content a:has(div[id='a']) ...

Accessing a peaceful API and displaying the outcome on a webpage using Node.js

I am currently working on a project that involves fetching data from a RESTful API and displaying the results on an HTML webpage using Node.js. While my code is running smoothly, I would like to ensure that the RESTful request is made every time the webp ...

Choose a JavaScript function by clicking on the HTML text

As a beginner in the world of coding, I have been diving into JavaScript, HTML, and CSS. Inspired by fictional supercomputers like the Batcomputer and Jarvis, I've challenged myself to create my own personal assistant to manage tasks, games, programs, ...

The JSON page does not display the image

I am facing an issue where the images are not displaying on both the JSON page and the HTML page, even though the image source name is being outputted. How can I ensure that the images show up on the HTML page? Thank you for taking the time to help. line ...

What is the best way to transfer the value of one directive attribute to another directive in AngularJS?

For instance: <custom-main> <custom-sub1 att-name="test"></custom-sub1> <custom-sub2></custom-sub2> </custom-main> JavaScript Source Code bosAppModule.directive('custom-main',[&apos ...

Guide on using Fetch API to send a request to a PHP file using the POST method

Hey everyone, I've recently started delving into the world of PHP and I encountered an issue while attempting to send a post request from my JavaScript file to my PHP file using the Fetch API. Upon making the request in my console, I received the foll ...

Encountering an unfamiliar statement

I'm trying to present my WordPress blog posts in a list using jQuery mobile and JSON API, but when I run the program I encounter the following error: Error: Syntax error, unrecognized expression: div class="entry">undefined ...){var t=e.nodeNa ...

The nodejs application seems to be encountering an issue as the /public/index.html file is not displaying on the

|project-name | client | public | index.html | server.js ↑ Structure of the Project The goal is to display the index.html file (located in the public folder) in server.js. [ server.js ] const express = require('express') const app ...

Having a solid grasp of React and Material UI, as well as familiarity with the concept of props and

For my react application, I utilize Material UI (@mui/material). However, I've come to realize that there might be some nuances in how the components interact with each other. For instance, if I nest a MenuItem inside a Box or a Link inside a Typograp ...

Turn off Vuetify designs specifically for Katex elements - Using common classes such as .accent can cause problems with styles

I have encountered an issue while using Katex with Vuetify. Certain classes such as accent or overline are causing conflicts between the two libraries, resulting in strange styling inconsistencies. For example, the overline characters are inheriting the ac ...

Enabling third party cookies in incognito mode for iframes: A step-by-step guide

When integrating a Next.js form deployed on Netlify into a React.js project using an iframe, I encountered the following error: Error Message The console displayed the error message: "Uncaught DOMException: Failed to read the 'localStorage' pro ...

Challenges Encountered with Random Image Generator in JavaScript

I am encountering an issue with a script that is supposed to change the default images to a random image each time the page is refreshed. However, I keep receiving an error stating that boxID is null. Why is boxID null? <script type="text/javascript" ...

Encountering the error "Cannot GET /login" while attempting to send a file through a post request in Express.js

I'm having trouble sending a new HTML file to the user after a successful login. Every time I attempt to send the file, I keep getting an error message saying "Cannot GET /login" on the page. Below is the section of code that's causing me diffic ...

handling a click event for an unresponsive ID (or so I assume)

After developing a pop-up button module using Bootstrap for integration into all product pages, I encountered a challenge that I need help with. The problem is outlined below. This is my first time posting here, so I'm open to feedback on the necessi ...

Expand the boundaries of the MUI Select to encompass a different element

Is there a way to extend the border of the MUI Select dropdown menu around the IconButton next to it? I have set up sorting options (A-Z, newest-oldest) using the Select component and included a button to reverse the direction (Z-A, oldest-newest). However ...

Having trouble with loading nested state in ui-router

Despite my efforts to find a solution online, I am stuck on a fairly basic issue. The router/index.html page I am working with appears to be correct, as there are no errors in the console. However, when the URL redirects to the login page, the entire page ...

When waiting for proxy leads to access the 'then' property, what should be my next move?

In my code, I am using a special Proxy to imitate a virtual object. The getter of this proxy returns values that are already prepared. After some exploration, I found out that when the proxy is awaited, it triggers the 'then' property of the pro ...

Accessing a parent class constructor object in NodeJS from the Child Class

I'm currently working on creating a Controller Class that will handle the initialization of all my routes using ExpressJS. Below is a simple example of what I have so far: class Test extends Controller { constructor(App) { const Routes = [ ...

Implement the use of `require` to update the `$watch` in an

As a new Angular user, I am facing an issue that involves having two directives in my HTML code like this: <parent-dir param="par"> <child-dir></child-dir> </parent-dir> And defining them in my JavaScript code as follows: In t ...