search

Home  >  Q&A  >  body text

How to download an image with user input name

I'm new to coding, especially JavaScript, so I decided to ask you guys to take a look and maybe help me find a solution. I want to download an image with a name entered by the user. I wish to download and rename a user specified file instead of a predefined URL (as shown in my example). I prefer downloading from the frontend. I tried it in JavaScript but it doesn't work...anyone have any ideas? Try it https://jsfiddle.net/8qj3czvg/...

[https://jsfiddle.net/8qj3czvg/][1]

P粉381463780P粉381463780513 days ago671

reply all(1)I'll reply

  • P粉722521204

    P粉7225212042023-09-09 09:33:18

    As someone has already commented, you should have a minimal reproducible example in your application; beyond that, you can try modifying the code in this way (note that additional name validation may be required ).

    HTML:

    <form>
        <input type="text" id="file-name" class="form-control form_style" placeholder="Enter Name">
    </form>
    

    Js:

    $(document).ready(function() {
        $('.is-hidden').click(function() {
            domtoimage
                .toPng(document.getElementById('content'), {
                    quality: 0.95
                })
                .then(function(dataUrl) {
                    let link = document.createElement('a');
                    let name = document.getElementById('file-name').value;
                    name = name ? name : "placeHolderName"; // checks whether the user has entered a file name
                    link.download = `${name}.jpeg`;
                    link.href = dataUrl;
                    link.click();
                })
        })
    })

    reply
    0
  • Cancelreply