Initiating a file download using HTML

When I try to initiate a download by specifying the filename, instead of downloading, it opens in a new tab. The code snippet below shows what I am currently using. Additionally, I am working on Chrome Browser.

<!DOCTYPE html> 
<html> 
   <body> 
      <p> 
         <a href="someFile.png" download="ID"> 
         <button type="button">Download</button> 
         </a> 
   </body> 
</html> 

Answer №1

To initiate the download of a file, start by creating an anchor element in your HTML document and then follow this sample code snippet:

var link = document.createElement('a');
link.href = 'file_path';  // Specify the path to the file you want to download.
link.download = 'file_name.png';  // Provide the desired name for the downloaded file.
link.click();

Answer №2

Everything seems to be in order

<a href="someFile.png" download>
    <button type="button">Download</button>
</a> 

It appears there might be a browser issue, consider changing your browser.

Furthermore, I recommend accessing the settings of Chrome and navigating to advanced options. Under Downloads, select clear for Auto Open preferences. Also, enable

Ask where to save each file before downloading
.

Answer №3

Chrome has made cross-origin downloads deprecated, please refer to chrome-65-deprecations. To make it work, ensure your image is from the same origin.

Below is a JavaScript example that works, but remember that your image must be on the same origin:

const btn = document.querySelector('#download_button');

btn.onclick = function() {
  const link = document.createElement("a");
      link.setAttribute("href", "https://homepages.cae.wisc.edu/~ece533/images/airplane.png");
      link.setAttribute("download", "airplane.png");
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
}
<!DOCTYPE html> 
<html> 
   <body> 
      <p> 
         <button id="download_button" type="button">Download</button>
      </p>
   </body> 
</html>

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

React - the method runs correctly when triggered by state changes, but runs twice when the parent component's state changes

As I work on constructing a page that requires data to be initialized upon mounting, updated based on responses from a websocket server triggered by a button click event, and the ability to disable and re-enable the button with a countdown for the user. M ...

Problem with Next.js router language settings

I have configured different locales for our application including uk and us. For the blog section, we can use either us/blog or just /blog for the uk locale. After switching to the us locale like this: (locale = "us") const updateRoute = (locale ...

Click the button to automatically insert the current time

Hello, I am new to scripting and seeking some guidance. I have a code that retrieves the current time and sends it to a MySQL database when a button is clicked. <form action="includes/data_input.inc.php" method="POST"> <!-- button - Start ...

Angular dynamically filling in a table with incomplete object data

I am currently working on a scientific project that involves displaying large amounts of data in tables. The experiments I'm working with have timestamps that follow this format: interface TimeData { time: string; data: {SD: string, SEM: string ...

An error occurred while trying to upload the image: Undefined property 'subscribe' cannot be read

Recently, I implemented a create post function that allows users to fill in the title, content, and upload an image. However, I encountered an issue where the progress bar fills up and the image gets uploaded to Firebase successfully, but it doesn't a ...

What steps can be taken to create a progress bar in the input field that spans the entire width of its parent div, reaching

I received assistance from a friend in creating this progress bar. Everything seems to be working well, except for the fact that the progress bar is not extending to the full width of the parent div. The new width after each input tag is entered using Java ...

Harnessing the power of two-way data binding in VueJS

I am looking to utilize Vue's two-way data binding to dynamically update the values of amount and total. The price of a given product is fixed. When users modify the amount, the total = amount * total will be automatically calculated. Similarly, users ...

Issue with Bootstrap.js causing mobile menu to not expand when toggled in Rails app

Despite adding the .toggled class, my hamburger menu is not expanding when I click on the mobile menu. I've tried adjusting the order of the required javascript commands, but it doesn't seem to be working as expected. Here are the steps I'v ...

Experiencing issues with the session not functioning properly on the login page

After setting up Centos 6.4 on my HP Server with PHP 5.3.3, Apache 2.2.15, and Mysql 5.1.69, I encountered login issues where it always fails. Here is the source code: index.php <? include "functions.php"; start_session(); session_destroy(); start_ ...

Extract the image source from this HTML retrieved using JavaScript

I need to retrieve the source URL of an image from a certain part of a document. Here is my current approach: var theImg = document.getElementById('imageDiv').innerHTML; The above code snippet returns something like this: theImg = <img src ...

Updating the text of a Mat-Label dynamically without the need to reload the page

In my application, there is a mat-label that shows the Customer End Date. The end date is fetched initially through a GET request to an API. Let's say the end date is 16-05-2099, which is displayed as it is. There is also a delete button implemented f ...

The date displayed in moment.js remains static even after submitting a new transaction, as it continues to hold onto the previous date until

I am currently utilizing moment.js for date formatting and storing it in the database This is the schema code that I have implemented: const Schema = new mongoose.Schema({ transactionTime: { type: Date, default: moment().toDate(), ...

Create CSS styles that are responsive to different screen sizes and

What is the best approach to ensure that these styles are responsive on any mobile device? nav ul ul { display: none; } nav ul li:hover > ul { display: block; } nav ul { background: #0066cc; background: linear-gradient(top, #0066cc 0%, #bbbbbb 10 ...

Attempting to minimize the number of jQuery calls within a Domino XPage

Trying to incorporate the 'DataTables' table plug-in for jQuery into a basic Domino XPage. Successfully loaded required libraries from CDN sources... JQuery: ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js DataTables: cdn.datatables. ...

A guide on effectively utilizing BehaviorSubject for removing items from an array

Currently, I am working on an Angular 8 application that consists of two components with a child-parent relationship. It came to my notice that even after removing an item from the child component, the item remains visible in the parent component's li ...

Sending a PHP variable to a modal using jQuery Ajax

I've encountered an issue with my jQuery ajax script. I'm struggling to pass a variable to the modal despite spending all weekend trying to debug it. Here is the link used to call the modal and the ID I want to pass: echo '<img src="./i ...

Tips for effectively modeling data with AngularJS and Firebase: Deciding when to utilize a controller

While creating a project to learn AngularJS and Firebase, I decided to build a replica of ESPN's Streak for the Cash. My motivation behind this was to experience real-time data handling and expand my knowledge. I felt that starting with this project w ...

Can a single page be used to send email?

My PHP form is currently sending data to another page, and the layout does not look good. I want to keep the form on the same page so that when a user fills it out, the information is submitted without redirecting. If any of the inputs are empty, I would l ...

Set my click event handler back to its default setting

I'm struggling with resetting a click function after it completes. How can I make sure it's ready to run again? $('body').on('click', '#ConfirmBet', function () { function randomImg() { var imgs = $(&apo ...

What could be the reason for the initial response appearing blank?

How can I retrieve all the comments of a post using expressjs with mongodb? I am facing an issue where the first response is always empty. Below is the code snippet: const Post = require("../models/posts"), Comment= require("../model ...