Downloading files (PDF, JPG, PNG) instead of automatically opening in a new tab

Is there a way to automatically download PDF and JPG files instead of opening them in a new tab like .docx files? Currently, when clicking on a PDF or JPG link, it opens in a new tab rather than downloading the file. The desired behavior is for these files to be downloaded upon clicking.

HTML (cannot be changed):

<div *ngFor="let action of documentActions">
   <button (click)="action.makeAction(element)">
       <mat-icon>{{action.name}}</mat-icon>
    </button>
</div>

URL example:

I have tried using FileSaver (NPM install file-saver) but the files still only open in a new tab rather than being downloaded.

Ts component:

declare var require: any
const FileSaver = require('file-saver');
(...)
        name: 'download',
        makeAction: (elem: DocumentListItem) =>
        {
          const url = elem.documentUrl;
          const filename = elem.name;
          FileSaver.saveAs(url,filename);
        }

I've also attempted: `

 makeAction: (elem: DocumentListItem) =>
        {
          window.open( elem.documentUrl);
        }

or

   makeAction: (elem: DocumentListItem) =>
        {
          window.location.href =  elem.documentUrl;
        }

` but no luck so far. Downloading docx files works without any issues. Any assistance with resolving this problem would be greatly appreciated.

Answer №1

If you were able to generate document URLs during the rendering phase, you could easily incorporate a basic HTML link with the download attribute:

<a href="[URL]" download="[optional suggested file name]">...</a>

For more information, take a look at the MDN documentation on the A element download attribute.

Answer №2

In order to initiate a download from a button click handler, you can simulate a plain link element with the click attribute. The href attribute of the link must be either relative in the same origin as the document or a blob: or data: URI.

Proof of concept that works on the top-level page (tested in current Chrome and Firefox), but not within the Stack Overflow sandbox iframe:

function downloadFile(url, filename) {
 var link = document.createElement('a');
 link.setAttribute('href', url);
 link.setAttribute('download', filename || '');
 document.body.appendChild(link);
 link.onclick = function() {
   setTimeout(function() {
     document.body.removeChild(link);
   }, 100)
 }
 link.click();
}
<p>(Not working in SO sandbox iframe.)

<p><button onclick="
    downloadFile('data:text/plain,test', 'button-download-test.txt')
    ">Download text dataURI</button>

<p><button onclick="
     downloadFile(document.location.href, 'button-download-test.html')
     ">Download this HTML file</button>

<p><button onclick="
    downloadFile('./probe.png', 'button-download-test.png')
    ">Download PNG file of the same origin</button>

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

The functionality of nested routing is not operating properly in react-router

I'm currently struggling to get my CollectionPage to render and match the URL correctly within my nested Route in React. Unfortunately, it doesn't seem to be working as expected! Here's a piece of code from my shop.component file that is be ...

Using a try-catch block within an axios call inside the then method in a Node

when I make the API call below, I encounter errors that I can't seem to handle properly. (node:5548) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent. (node:5548) [DEP00 ...

Node.js: Understanding the issue of a mysterious null value in JSON responses sent to clients

As a beginner in the world of Node.js and JavaScript, I have been struggling to find a solution to my problem even after extensive searching. My current challenge involves sending a JSON object to a Node.js server with an array of 2 elements (longitude an ...

Is it possible to construct an Angular project without altering the file size limit?

The budget of 40.00 kB fell short by 60.66 kB for a total of 80.66 kB. I've been grappling with the issue of exceeding the max file limit for anyComponentStyle. While working with Material UI and utilizing indigo-pink.css in my component scss, I&apo ...

Tips for displaying a removal option and eliminating an uploaded document

I need assistance in implementing file uploading using dropzone.js. I am struggling to find a solution on how to delete uploaded files. Here is the code snippet: index.php <div class="container"> <div class="file_upload"> <form action= ...

TypeScript and Angular: Harnessing the Power of Directive Dependency Injection

There are multiple approaches to creating Angular directives in TypeScript. One elegant method involves using a static factory function: module app { export class myDirective implements ng.IDirective { restrict: string = "E"; replace: ...

What are the steps to configure a Twilio device in an Angular application to handle incoming calls with an API built in .NET 6?

I have encountered an issue with incoming calls. The API is in .NET 6, and the frontend is an Angular app for a multi-tenant application. I've set up a Twilio device in the Angular app and created an incoming webhook on Twilio with the webhook endpoin ...

Looking for the quickest hash and salt method for IP addresses in Node.JS?

Currently, there are many stipulations regarding the tracking of user data such as unique visits and returning users. An issue arises in certain regions where IP addresses are considered sensitive personal information. To continue identifying unique user ...

How can Javascript or Jquery determine the specific event assigned to an object?

Is it possible to retrieve the properties of HTML elements using their name or id? For example: document.getElementById('id').value; //Accessing element property in JavaScript $('#id').attr('class'); // Accessing correspond ...

Why is it that my React app is on a different port than the Express server that it listens to?

As I'm working on my React app, it currently runs on the default port http://localhost:3000/. However, when I need to communicate data from the client to the server, I have to listen on a different port. Take a look at the below code snippet: const ex ...

What is the most effective method for updating a className in Next.js using CSS Modules when a button is activated?

Looking to create a responsive navigation bar that transforms based on screen size? When the width reaches 600px, I'd like to hide the links and instead show a clickable nav button that reveals those options. Upon inspecting my list elements in the c ...

Error: Required prop type check failed: The `children` prop in `InputAdornment` component is mandatory, but it is currently undefined

Whenever I execute my React.js front-end, I encounter this warning: index.js:1446 Warning: Failed prop type: The prop `children` is marked as required in `InputAdornment`, but its value is `undefined`. in InputAdornment (created by WithStyles(InputAdo ...

Sharing JSON data between two Backbone views

Could you provide some guidance on how to pass dynamic JSON data from one view to another? In the initial view, I am creating the JSON object using the following syntax: json.push({ first: value, second: value }); ...

Loading 500,000 entries individually into mongodb results in a memory overflow

I am currently working on inserting a large volume of 500,000 records into a MongoDB collection. These records are stored in a CSV format, parsed, and then saved to an array. I am using a recursive function to insert the records one by one, and when a reco ...

The Stylish Choice: Materialize CSS Dropdown Selector

I am currently integrating Materialize CSS into my application and have used media queries to ensure that the layout is responsive. However, I am facing an issue with a select dropdown element. It works fine on laptops but does not allow for selecting any ...

What's causing this MUI React data grid component to be rendered multiple times?

I have developed a wrapper for the MUI Data Grid Component as portrayed: Selection.tsx: import * as React from 'react'; import { DataGrid, faIR, GridSelectionModel } from '@mui/x-data-grid'; import type {} from '@mui/x-data-grid/t ...

Struggling with a Bootstrap v5.0.2 Modal glitch? Let's dive into a real-life case study to troub

I am seeking assistance with a problem that I am encountering. I am currently using Bootstrap version 5.0.2 (js and css). Despite coding all the required parameters, I am unable to make the modal functionality work. I have been trying to figure out what&ap ...

Avoiding the use of apostrophes in jQuery or JavaScript

I need to show the text below for the <span> element. What's the best way to handle single quotes in this case? $("#spn_err").text($('#txt1').attr('value')+" is not valid"); The desired message format is 'ZZZ' is ...

From what source does the angular framework retrieve its 'data' information?

--- Consider this code snippet from a specific file --- angular.module('storyCtrl', ['storyService']) .controller('StoryController', function(Story, socketio) { var vm = this; Story.getStory() .success(func ...

Unable to create properties for a class that is being exported

When attempting to instantiate an exported class, I am encountering the following error: TypeError: Cannot set property '_db' of undefined This is how I am creating and exporting the class: const mongodb = require('mongodb').MongoC ...