Tom Smykowski
Tom Smykowski

Reputation: 26089

How to change save image to file default name?

I have a canvas HTML5 tag that is created by Caman.js.

When I click right in FF and save to file the default name for the file is canvas.png. Since I create a lot of files and need to save them this is unfortunate, because I need to set the different name for each.

What I would like to accomplish is that when saving first image save to file dialog shows firstfile.png and second secondfile.png and so on. So I don't need to change the name in the save dialog window.

How to change the default name of save to file dialog in FF using HTML and JS?

Upvotes: 10

Views: 11285

Answers (6)

AutoBaker
AutoBaker

Reputation: 1297

I know the question is tagged HTML and JS but I needed to do this and for me it made sense to do it in PHP. If you are able to write HTML and JS then you're likely to be able to write PHP as well so maybe this will be helpful to someone.

<?php 
$url = "https://yourwebsite.com/assets/image.png";
$contents = file_get_contents($url);
$myfile = fopen("images/custom_name.png", "w") or die("Unable to open file!");
fwrite($myfile, $contents);
fclose($myfile)

?>
<a href="https://yourwebsite.com/images/custom_name.png" download>
    <button>Download image</button>
</a>

And then you could easily wrap this in a loop for multiple images with the loop integer becoming part of the filename.

Upvotes: -1

Kevin Thoriya
Kevin Thoriya

Reputation: 13

Hello looks like its possible if server sends a file name

<img src="https://s3-eu-west-2.amazonaws.com/se-odoo-stage-1/4e35c1945e3eb656548f6ff7a0d33774c1b011f9">  TRY

<br>

<img src="https://s3-eu-west-2.amazonaws.com/se-odoo-stage-1/220347c51e4b24358d2e1a85dc2574e8a15a4014"> TO SAVE


<br>

<img src="https://s3-eu-west-2.amazonaws.com/se-odoo-stage-1/e1e9ffcaa77b5a1efc742d1031325a6cfe6efccf"> THIS IMAGES

if you try to save this image it autosaves as google

now if you go to network tool and https://s3-eu-west-2.amazonaws.com/se-odoo-stage-1/4e35c1945e3eb656548f6ff7a0d33774c1b011f9 analyze response header of this request in which you can find Content-Disposition: attachment; filename=google. check the response header content-disposition , filename so if filename send by server somehow then it can be possible to say to set default image name.

Upvotes: 0

shramee
shramee

Reputation: 5099

It's not quite possible to change default name, but we can create an a tag and give it canvas data and set download attr to filename of choice, and show it like a menu replacing default menu...

Default and right clicked states

Code will look something like this...

jQuery(function($) {
  $('<a id="download-canvas">Save as image</a>').appendTo('body'); // Adding the tag to body
  var link = $('#download-canvas')

  $('body').click(function(e) {
    link.hide(0) // Hide the link on clicking anywhere else
  })
  $(document).on("contextmenu", function(e) {
    link.hide(0)
    if (e.target.nodeName == "CANVAS") { // Proceed for CANVAS nodes only
      e.preventDefault(); // Dont show default menu

      link
        .attr({ //Set the attributes for link
          href: e.target.toDataURL(),
          download: 'my-file.png'
        })
        .css({ // Position the link to current mouse position
          top: e.clientY,
          left: e.clientX,
          display: 'block'
        });

    }
  });
});

///////////////////////////////////
// Just drawing something on canvas
var canvas = document.getElementById('canvas-id'),
  ctx = canvas.getContext('2d');
ctx.fillStyle = '#0cf';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#fff';
ctx.font = '60px sans-serif';
ctx.fillText('Hi from Canvas!', 10, canvas.height / 2 - 15);
ctx.font = '26px sans-serif';
ctx.fillText('Just right click me to download ;-)', 15, canvas.height / 2 + 35);
/* Position the tag absolute and make it look pretty */

#download-canvas {
  display: block;
  background: #fff;
  padding: 7px;
  font: 14px sans-serif;
  color: #555;
  border: 1px solid #ccc;
  position: absolute;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas width="500" height="300" id="canvas-id">Sorry, Your browser doesn't support canvas.</canvas>

Upvotes: 2

fedeghe
fedeghe

Reputation: 1318

I successfully did it creating on the fly an anchor hidden tag with right attributes, appended, trigger click, and hide it, try it out, just take care about the id attribute of the canvas element:

var basename = 'myfile';
function downloadAs = (function () {
    var n = 1;
    return function () {
        var afake = document.createElement('a'),
            cnv = document.getElementById('canvasId'),
            img = cnv.toDataURL("image/png");
        afake.href = img;
        afake.download = basename + "" + n++;
        afake.style.display = 'none';
        document.body.appendChild(afake);
        afake.click();
        window.setTimeout(function () {
            document.body.removeChild(afake);
        }, 200);
    };
})();

Here You can find a working example... this is an old experiment I wrote 2yago and almost abandoned :(, btw what is important now is the fourth last icon 'export image' (a tooltip should appears) click, name it and press Export, ...humm.. yes ...if You draw something with the mouse before exporting maybe is better :D

Upvotes: 2

user1693593
user1693593

Reputation:

How to change the default name of save to file dialog in FF using HTML and JS?

The simple answer is that we can't.

The names are generated internally in the browser and we have no API access to this from an ordinary web page, and therefor can't change this behavior.

There are several reasons for not having direct access to the default context menu, one being security.

Extensions

One work-around though is to write a plugin/extension for the browser and provide a custom context menu item which you can then give the desired behavior.

Or use some existing ones like this or this - these are randomly selected just meant as examples. You may be able a better fit going through the add-on collections.

Download attribute and context menu

If you are controlling the page you want to save the images from, you could also provide a custom context menu which allows you to save images using the A-tag and the download attribute which allows you to set a filename.

You would need to convert the image to an Object-URL or Data-URI and set that as source for the A-tag.

Some may object to using custom context menus for various reasons, but if this is for local usage there is no good reason saying you can't, and in other cases a good UX approach can inform the user of this behavior removing any surprises.

Context menu example using CamanJS

Added a minimalist example to pop up the menu with a link and filename. The example uses CamanJS using the toBase64() method.

Since CamanJS replaced the original element it is important to attach event handlers after canvas has replaced them as otherwise the handler will die together with the original element in the sense they are no longer available.

Caman(img, function() {
  var me = this;
  
  // from inside callback as img is now a different element
  img.oncontextmenu = function(e) {
    e.preventDefault();                           // prevent default action
    lnk.download = lnk.innerHTML = "Myfile.jpg";  // set file and link name
    lnk.href = me.toBase64();                     // get Data-URI from CamanJS
    menu.style.cssText =                          // show the menu
      "left:" + e.clientX + "px; top:" + e.clientY + "px; display:block";
  };
});

window.onclick = function() {menu.style.display="none"};
#menu {
  position:fixed;
  background:#444;
  padding:4px 7px;
  box-shadow:3px 3px 3px #000;
  display:none;
  }
#menu a {color:#fff;font:14px sans-serif}
<script src="http://cdnjs.cloudflare.com/ajax/libs/camanjs/4.0.0/caman.full.min.js"></script>
<img id=img src="//i.imgur.com/67E6Ujdb.jpg" crossOrigin="anonymous">
<div id="menu">
  <a id="lnk"></a>
</div>

NOTE: may not work in Stacksnippet with Firefox (seem to be an issue with Stacksnippet). Here is a alternative fiddle link in that case.

Upvotes: 11

krish
krish

Reputation: 881

To change the default name when Save AS dialog is not directly possible, But there is a workaround

You can specify the file name for file to be downloaded using Download Attribute in a tag like this

<a href="ImageLocation" download="filename">

Convert you canvas to data url and assign it to href of a tag

var canvas = document.getElementById('canvasId');
var yourlink= document.getElementById('linkId');
var dataURL = canvas.toDataURL();
yourlink.href=dataURL;

Upvotes: 8

Related Questions