how to send png image from server to display in browser via ajax

前端 未结 4 635
别跟我提以往
别跟我提以往 2021-01-04 09:37

I have been having a hard time with what must be an incredibly normal task. I upload and save images to my web server and save the path to the file in MySQL data base (this

相关标签:
4条回答
  • 2021-01-04 10:22

    You could display a default "no access" image to users who are forbidden to access the image:

    <?php
    
    $file = $_GET['file']; // don't forget to sanitize this!
    
    header('Content-type: image/png');
    if (user_is_allowed_to_access($file)) {
        readfile($file);
    }
    else {
        readfile('some/default/file.png');
    }
    

    And, on the client side:

    <img src="script.php?file=path/to/file.png" />
    

    Alternatively, if you really really want or need to send the data via Ajax, you can Base64 encode it:

    <?php
    
    echo base64_encode(file_get_contents($file));
    

    And place the response in an img tag using the Data URI scheme

    var img = '<img src="data:image/png;base64,'+ server_reponse +'"/>';
    

    Given that the Base64 encoded data is significantly larger than the original, you could send the raw data and encode it in the browser using a library.


    Does that make sense to you?

    0 讨论(0)
  • 2021-01-04 10:35

    Instead of getting get_image.php through AJAX, why not just use:

    <img src="get_image.php" />
    

    It's practically the same thing. You can just use AJAX to update the <img> dynamically.

    0 讨论(0)
  • 2021-01-04 10:40

    You can actually embed image data inside the img tag in the browser, therefore ajax code could look like this:

    $.ajax({
        url: get_image.php,
        success: function(image_string){
            $(document.body).append("<img src='data:image/gif;base64," + base64_encode(image_string) + "' />);
        }
    });
    

    Note that you will need to write this base64_encode function. Have a look at this question - the function is given there.

    0 讨论(0)
  • 2021-01-04 10:42

    You can't do it via ajax.

    You could do something like this:

    <img src="script.php?image=image_name" />
    

    Then use JavaScript to change the query string.

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