Download a picture OnClick

后端 未结 4 1126
感情败类
感情败类 2021-01-06 14:02

How do you actually download a picture when you click on it? Is there some kind of a javascript code to do just that? Here is how i show the image with pure HTML.

         


        
相关标签:
4条回答
  • 2021-01-06 14:16

    I trick this out a bit - I zip the picture and put it somewhere. Then, instead of using a fancy script or server-side stuff, I make the picture's link the location of the .zip file. The user get's warned/asked if they want to download this zip and voila...

    But this is usually in an area where the user is someone who would want the image...

    0 讨论(0)
  • 2021-01-06 14:17

    Assuming by "download" you mean "Cause the user's browser to throw up the 'save or open' dialogue" — you can't.

    You could link to another URL offering the same file but with the Content-Disposition header set to attachment. The specifics of how you would provide such a resource at that URL would depend on the server side capabilities on offer to you.

    0 讨论(0)
  • 2021-01-06 14:21

    Most people right-click on the image and choose "Save image as..."

    The alternate is to link to use a server-side script that sets a "Content-type" and "Content-disposition" header. In PHP, that would be something like this example from the docs:

    header('Content-Type: image/png'); // or 'image/jpg' or 'image/gif'
    header('Content-Disposition: attachment; filename="filename.png"');
    readfile('original.png');
    

    UPDATE: Since you say the image is generated by a PHP script in the first place, there are a few options:

    • Put the URL (sig.php?...) as the parameter to readfile. This will mean double processing for anyone who clicks to download.
    • Cache the output from your image generation script to the filesystem, then pass that file to readfile.
    • Edit the image generation script to accept an extra parameter like mode=download and then where you are about to output the image, if the parameter is present, set those two headers above.
    0 讨论(0)
  • 2021-01-06 14:23

    Do you want to open the picture in a new window/tab? Or do you want to download it to the users computer? If you want the user to save the image, then you need to set the content-type of the file they receive:

    <?php
    $file = $_GET['file'];
    
    header("Content-Type: application/octet-stream; ");
    header("Content-Transfer-Encoding: binary"); 
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    readfile($file);
    ?>
    

    Remember to check the input so people can't download source files.

    0 讨论(0)
提交回复
热议问题