Download a picture OnClick

后端 未结 4 1212
感情败类
感情败类 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: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.

提交回复
热议问题