Error encountered while attempting to download PDF file (blob) using JavaScript

Recently, I have been utilizing a method to download PDF files from the server using Laravel 8 (API Sanctum) and Vue 3. In my Vue component, I have implemented a function that allows for file downloads.

const onDownloadDocument = (id) => {           
   axios.post('/api/document/download', {id: id},{
     responseType: 'blob'
   }).then(response => {
     let filename = response.headers['content-disposition'].split('filename=')[1]               
     dLink.value.href = window.URL.createObjectURL(response.data)
     dLink.value.setAttribute('download',filename)
     dLink.value.click()
   }).catch(error => {
      console.log(error)
   })

In this function, 'dLink' is designated as a link reference.

const dLink = ref(null)

within the template:

<a ref="dLink"/>

This approach has been working flawlessly until recently. After updating the project through composer and npm, I encountered an error when attempting to download a file:

contract.js:1049 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'responseType')

Any insights on why this might be occurring? The API backend does return the file as a blob format.

return Storage::download($document->filename);

Answer №1

To start, create a blob and insert your response into it.

As mentioned in the comment, there is no need to link it to an actual anchor tag; instead, generate an element, attach it to the body, simulate the click, and promptly remove it.

const blob = new Blob([response], {type: 'application/pdf'})
if (window.navigator['msSaveOrOpenBlob']) {
    window.navigator['msSaveBlob'](blob, filename)
}
else {
    const elem = window.document.createElement('a')
    elem.href = window.URL.createObjectURL(blob)
    elem.download = filename
    document.body.appendChild(elem)
    elem.click()
    document.body.removeChild(elem)
}

Answer №2

After some experimentation, I found that by specifying to axios that the expected response is a blog file, everything fell into place:

axios({
  url: 'http://localhost:5000/endpoint?',
  method: 'GET',
  responseType: 'blob', // <= extremely important
}).then((response) => {
  const url = window.URL.createObjectURL(new Blob([response.data]));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', 'file.pdf');
  document.body.appendChild(link);
  link.click();
});

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

Having trouble retrieving POST data with the Webextensions API

Looking to retrieve POST data using a Webextensions API on page load. Implemented a background script with the code below: browser.webRequest.onBeforeSendHeaders.addListener( getPostData, { urls: ['<all_urls>'], types: ["main_fr ...

Determining the file path in HTML5

Can anyone help me with retrieving the file path using html5 javascript once a user selects a file? I require the file path for a specific scenario: In this case, the user uploads a file and pauses it (currently only supported by Mozilla browsers), then c ...

Vite, Vue, and Vuetify: A multitude of inexplicable network requests happening

Excited to share that I've started working on my very first Vue project - a Simple CRUD Application. Utilizing Vite, Vue3, and Vuetify, with PNPM as the Package Manager. Development has been smooth so far, without encountering any major issues. Howev ...

Bringing back a Mongoose Aggregate Method to be Utilized in Angular

I'm having trouble returning an aggregate function to Angular and encountering errors along the way. I would really appreciate some assistance with identifying the mistake I am making. The specific error message I receive is Cannot read property &apos ...

Expanding the properties of an object dynamically and 'directly' by utilizing `this` in JavaScript/TypeScript

Is it possible to directly add properties from an object "directly" to this of a class in JavaScript/TypeScript, bypassing the need to loop through the object properties and create them manually? I have attempted something like this but it doesn't se ...

Sending data using Ajax to the server-side code in ASP.NET

Struggling to successfully pass a series of values through Ajax to a code-behind method in order to insert the data into a database table. However, encountering issues where string variables are being received as empty strings and int variables as 0. The ...

Exploring ways to run tests on a server REST API using testem

When using Testem, I have a config option called serve_files that handles serving the client-side code for me. However, I also need to run my server because it includes a REST API that the client side relies on. Is there a way to configure Testem to launc ...

Ways to update the component's state externally

I'm new to Next.js (and React) and I'm attempting to update the state of a component from outside the component. Essentially, I am conditionally rendering HTML in the component and have a button inside the component that triggers a function to se ...

Quiz results are incorrect

I've been working on creating a quiz application using JavaScript only, but I'm encountering an issue with the scoring. Initially, I set the correct variable to 0 and intended to increment it by 1 each time a correct answer is selected. However, ...

use element ui tree and vue to filter files according to selected folder

Utilizing the element UI treeview to showcase folders. Each folder or its child folder contains files that need to be displayed based on folder selection. While it's easy to filter and list out these files in a normal list, I am facing challenges with ...

A guide on changing a plus sign into a minus sign with CSS transition

Is there a way to create a toggle button that changes from a plus sign to a minus sign using only CSS, without the need for pseudo-elements? The desired effect is to have the vertical line in the "+" sign shrink into the horizontal line. While I know it& ...

The 404 error message was encountered when attempting to fetch the Ajax

I am experimenting with using Ajax to load all images from a local folder onto my HTML page. The code I am referring to comes from this question. I am running the files on a (Tomcat 8.5) server in Eclipse and opening the URL in Google Chrome. However, when ...

Using localStorage in Next.js, Redux, and TypeScript may lead to errors as it is not defined

Currently, I am encountering an issue in my project where I am receiving a ReferenceError: localStorage is not defined. The technologies I am using for this project are Nextjs, Redux, and Typescript. https://i.stack.imgur.com/6l3vs.png I have declared ...

What is the best way to generate bootstrap rows from this code in React JS?

In my current array of objects, I have twelve items: { data:[ { type:"tweets", id:"1", attributes:{ user_name:"AKyleAlex", tweet:"<a href="https://twitter.com/Javi" target="_blank"> ...

Clicking in Javascript can hide the scroll and smoothly take you to the top of the page

For my website, I found this useful tool: It's been working great for me, but one issue I've encountered is that when I click on a picture using the tool, its opacity changes to 0 but the link remains in the same spot. I'm trying to figure ...

What is the best way to manage user sessions for the Logout button in Next.js, ensuring it is rendered correctly within the Navbar components?

I have successfully implemented these AuthButtons on both the server and client sides: Client 'use client'; import { Session, createClientComponentClient } from '@supabase/auth-helpers-nextjs'; import Link from 'next/link'; ...

Exploring the Power of Nuxt's asyncData Feature for Handling Multiple Requests

Within my application, there is a seller page showcasing products listed by the specific seller. Utilizing asyncData to retrieve all necessary data for this page has been beneficial in terms of SEO. asyncData ({params, app, error }) { return app.$axi ...

The issue of Next.JS fetch not caching data within the same request

I am faced with a straightforward setup where a Next.JS server-side component is responsible for fetching and displaying a post. The challenge lies in setting the page title to reflect the title of the post, requiring me to call my posts API endpoint twice ...

Unable to display Apexcharts bar chart in Vue.js application

Struggling to incorporate Apexcharts into my Vue.js site, but unfortunately, the chart isn't appearing as expected. -For more guidance on Apexcharts, check out their documentation Here HTML <div class="section sec2"> <div id="chart" ...

The output generated by grunt-contrib-handlebars differs from that of the handlebars npm task

Looking for some help with a problem similar to the one mentioned in this Stack Overflow question. Since that question hasn't been answered yet, I decided to create my own post. I'm currently attempting to precompile my handlebars template files ...