How does js download image files instead of opening them in a new window?

I already have the address of the picture (url)
now I need to click the button and open the download dialog box to download the picture file
but if you do this:

var a = document.createElement("a");
a.href = this.editBrand.contract; 
a.download="file"; 
a.click();

only opens a new window, not the download dialog box.
Thank you

Dec.18,2021

a-HTML attribute

download attribute
this property instructs the browser to download URL instead of navigating to URL, so the user will be prompted to save it as a local file.
if the property has a value, it will be used as the pre-filled file name in the save prompt (users can still change the file name as needed). There is no limit to the allowed values, but / and are converted to underscores. Most file systems restrict some punctuation in file names, and browsers adjust the recommended names accordingly.

Note:
this attribute applies only to homologous URLs.

applies only to homologous.

a tag's download attribute is added. If src is the address of the picture, you can download the picture. It can only be downloaded from the address of the same origin.


the easiest way

 <button onclick="down()"></button>
  <script>
    function down() {
      var a = document.createElement('a');
      a.href = 'timg.jpg'; //
      a.download = "file.jpg"; //
      document.body.appendChild(a);
      a.click();
    }

you can take a look at this article
https://www.jianshu.com/p/8ad.


var a = document.createElement('a');
a.download = this.editBrand.contract;
a.click();

document.body.appendChild ()


only Firefox and Chrome support the download attribute.
can refer to https://www.jianshu.com/p/8ad.


has the landlord solved it? I also encountered the same problem, with only one file address


actually directly window.location = 'address'; it's easy to use, isn't it?
first of all, is your picture address or the download address of the picture?
if it's the download address, there should be no problem
but if it's just the picture address, then it must be opening the picture instead of the download window
clipboard.png

clipboard.png
a.target = '_blank'
clipboard.png

clipboard.png
you can add an a.target ='_ self';
try it or directly window.location = 'address';
I feel good

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b34be4-342ea.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b34be4-342ea.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?