html The "download" attribute causing a new tab to open rather than initiating a

I have a website built with Angular 4, where users can download images from an Amazon S3 bucket. However, I encountered an issue wherein instead of downloading the image, it opens in a new tab. I've tested this problem on different browsers such as Firefox, Chrome, and Safari.

Here's the code snippet from the template:

<a mat-raised-button color="accent" [href]="downloadPath" download matTooltip="Download file to pc." *ngIf="isFinalReport()">
    <mat-icon>file_download</mat-icon>
    DOWNLOAD
</a>

The download path looks something like this:

I have also tested it with various images sourced from the internet, but unfortunately, none of them work. Oddly enough, if I try using a local image (C:/Users/User/Desktop/images/image.jpg), it works perfectly fine.

Do you have any insight into why this issue is occurring and how to resolve it? If you require additional information, please let me know.

Thank you.

Answer №1

To directly obtain the desired image, you may attempt using the following code:

<a [href]="javascript:downloadImage(downloadLink);"></a>

function downloadImage(downloadLink) {
  this.mediaService.getImage(downloadLink).subscribe(
    (res) => {
      const newElement = document.createElement('a');
      newElement.href = URL.createObjectURL(res);
      newElement.download = title;
      document.body.appendChild(newElement);
      newElement.click();
    }
  );
}

Answer №2

After conducting thorough research, I came to the conclusion that utilizing the backend is the most effective solution for this particular problem. My objective was to create an anchor tag that, upon being clicked, would initiate a download of the S3 URL. However, instead of downloading the file, it would open in a new tab. This issue can likely be attributed to one or two factors. Firstly, browsers typically do not permit direct cross-origin downloads. Secondly, your Response Content Disposition may also play a role. To address this matter, I have devised the following approach to enable direct downloading from S3 to the filesystem:

Backend (I personally employ Django and boto3):

    def get_file(self, obj):      
        client = boto3.client('s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
                              aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)

        return client.generate_presigned_url(
            'get_object',
            Params={
                'Bucket': settings.AWS_STORAGE_BUCKET_NAME,
                'Key': obj.key,
                'ResponseContentDisposition': 'attachment',
            },
            ExpiresIn=600)

Frontend (utilizing Angular):

<a [href]="what_i_returned_from_backend" [download]="answer.png" target="_self" rel="noopener noreferrer">Download</a>

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

How to dynamically customize styling on md-tab in Angular2-material?

Styling material design components can be challenging, especially when trying to dynamically set styles on an md-tab based on its active or archived state. I'm looking to make the tab header text italic and change its color to indicate whether it is a ...

Issue with Angular 4 Bootstrap Carousel

I encountered a console error that I couldn't resolve while working on my project. The technology stack involves Angular 4 and Bootstrap. Unfortunately, my frontend developer is unavailable this weekend, and I'm unsure if there are any missing d ...

How can I prevent duplicate IDs when submitting a form through AJAX within a while loop?

While submitting a form using Ajax within a while loop, I encountered an issue where the same form ID is being used multiple times due to the loop. As a result, the form only submits once. I believe that I need to generate a unique ID for each iteration of ...

What is the method for HTML inline handlers to retrieve the global window object and the variables contained within it?

During my coding test, I encountered an interesting scenario. I had a function called write and used a button with an inline onclick handler to trigger the write() function. function write(text) { alert(text) } <button onclick='write("Some tex ...

Text Alignment Issue in Icon Bar of Zurb Foundation 5

There's an unusual problem I'm encountering with the alignment of text under the icon bar not being properly centered below the icons. Here is a snippet of the code: <div class="row"> <div class="small-12 columns"> < ...

Section separators within ordered lists

I am currently working on creating a "reference document" section within a Webhelp Responsive website that I have developed using a DITA map. My goal is to display a typical document list with unique reference numbers ([1], [2], [3]...[N]) followed by rele ...

Manipulating div position interactively with vanilla javascript during scroll

I'm trying to create an effect where an image inside a div moves vertically downwards as the user scrolls, stopping only at the end of the page. I've attempted a solution using a script from another post, but it doesn't seem to be working. ...

Styling Collapse Text in Bootstrap Framework

I have a question about the "Accordion example" in the Bootstrap Collapse Component. My query is regarding removing the underline from the text "Collapsible Group Item" 1-3 when they are activated. Normally, this text is not underlined, but upon hovering, ...

It is imperative that the 'Access-Control-Allow-Origin' header value in the response is not set to '*' when the request's credentials mode is 'include'

I am currently working on establishing a connection using socket.io between Angular and a Node.js Server Within Angular, I have set up a new socket by importing socket.io-client and connecting it as follows: import * as io from 'socket.io-client& ...

connecting and linking template content with an Observable

I have a CRUD page that needs to be updated after every operation. I have implemented Observable and the CRUD functions (specifically Add and Delete) are working fine, but I need to manually refresh the page to see the changes reflected. After trying to ...

Animating Angular ng-template on open/close state status

I am looking to add animation when the status of my ng-template changes, but I am unable to find any information about this component... This is the code in my report.component.html <ngb-accordion (click)="arrowRotation(i)" (panelChange)="isOpen($even ...

Is it possible to customize the placement of the login or register success message?

I would like to display a message indicating whether the login/register process was successful or not above my form. I am using Boostrap 3 along with some PHP functions. The message appears above my navbar but vanishes after 3 seconds, which is a bit anno ...

The ngx-translate Angular translation file is being loaded twice unnecessarily

Upon reviewing the network tab in the browser's developer tools, I discovered that my Angular app translation file is being loaded twice. Is there an issue with this? Should it be loading multiple times? https://i.stack.imgur.com/vcKm1.png ...

I'm stuck trying to figure out all the parameters for the MapsPage component in Angular 2

Currently, I am utilizing Angular2 with Ionic2 for my mobile app development. Everything was working flawlessly until I decided to incorporate a new module for Google Maps navigation. Specifically, I am using phonegap-launch-navigator for this purpose. The ...

What are the implications of using subresource integrity with images and other types of media

Subresource integrity is a fantastic method for securely using third-party controlled HTTP-served resources. However, the specification currently only covers the HTMLLinkElement and HTMLScriptElement interfaces: NOTE A future iteration of this spec may i ...

What is the best way to display a User's name as text on a Django page without having to refresh the page?

I'm currently working on a feature where I need to show a User's name on top of a form box when they enter their Employee number, all without needing to refresh the page. Here's how it should work: once the User fills in their Employee numb ...

The custom component at the beginning of the MDX file in a Next.js project is not adhering to the

My nextjs project is running on the following versions: "@mdx-js/loader": "^2.1.5", "@mdx-js/react": "^2.1.5", "@next/mdx": "^12.1.6", "next": "^12.1.6", Within my project, I ...

What is the best way to display text outside of the current div container?

When I include the "Y" in the code snippet below, $title1 and $title2 are positioned outside of the div and centered against the width of the page. However, without the "Y", the text shifts up and aligns with the address class instead. It's puzzling w ...

Issue with Font Requests in Browsers when Using Angular 10 and SCSS with @font-face

I have a project built with Angular 10 that utilizes SCSS for styling. In my _typography.scss file, I have defined some @font-face rules pointing to the font files located in the assets/fonts directory. However, when I run the application, the browser does ...

Encountering an error in Angular where the property does not exist in type

Struggling to create a collapsible menu within my header component in an Angular project, I've hit a snag with proper JSON formatting. The error message that keeps popping up reads: Error: src/app/components/header/header.component.html:48:49 - error ...