php - 通过 PHP 返回图像并使用 AJAX 设置为 src

标签 php jquery ajax image file

当我尝试显示多个图像时遇到一些问题(它不适用于一张图像,因此不可能显示多个图像),我正在做的是使用我的 AJAX 功能从我的数据库中恢复,所有表图像中的图像位置字符串。然后它调用另一个名为 setImages() 的函数,该函数接收图像位置的这些字符串,我使用迭代这些字符串(使用 jQuery 的 .each())来触发 AJAX调用名为 image.php?img=[data] 的 php 脚本的请求。 data 是包含图像位置的字符串,所以我有类似下面的代码:

问题是我的js的setImages()不显示图像

PHP 文件:

<?php

    $init="/var/Imagenes/cursos/";
    $img=$_GET['img'];
    $path=$init.$img;
    echo $path;
//el path debe ser autores/ or cursos/
    $name="azure";
/*
    header("Cache-Control: no-cache, must-revalidate");
    header("X-Sendfile: $path");
    header("Content-Type: image/jpeg");
    header("Content-Disposition: inline; filename='archivos'");
*/
//el nombre de la base de datos de la imagen
header("Cache-Control: no-cache, must-revalidate");
if((isset($path)&& !is_null($path))){
    header("X-Sendfile: $path");
    if(strpos( $img, ".png" )||strpos( $img, ".PNG" )){
        header("Content-Type: image/PNG;base64");
    }
    elseif(strpos( $img, ".jpg" )||strpos( $img, ".JPG" )){
        header("Content-Type: image/jpg;base64");
    }
    elseif(strpos( $img, ".jpeg" )||strpos( $img, ".JPEG" )){
        header("Content-Type: image/jpeg;base64");
    }
    else{
        return "error.jpg";
    }
    $newimg=rand(1000 , 9999 );
    header("Content-Disposition: inline; fileimg= $newimg-$img");
    exit();
}
else{
    echo "no se pudo realizar la consulta";}

JS代码:

函数listImgCursos工作正常...

function listImgCursos(identificador) {
           var resultado= $.ajax({
                url: consultaBasica,
                cache: false,
                type: 'POST',
                data : { action: "imgCursos"}
            }).then(
                function(data){// Success
                    var flagErrFound = false;
                    var nf404 = "" ;
                        $.each(data,
                            function(index,datos){
                                if((datos['id']===null)||(datos['img']=="")||(datos['img']==null)){
                                    nf404 = datos['id'];
                                    flagErrFound= true;
                                }//if close
                            }//function close
                        )//each close
                        if(flagErrFound===true){
                            error = {error: "CX02", msj: "Failed to get data from records.", data: nf404 };
                            return $.Deferred().reject(error);
                            }
                        else
                            return data;
                    },//function sucessful
                function(){// fail
                    error = {error: "CX01", msj: "Failed to execute ajax"};
                    return $.Deferred().reject(error);
                    }//function fail
                );//then;  
            resultado.done(
                function (data){//success
                   setImages(data);
                }//function DONE
            );
            resultado.fail(
                function(e){//function fail
                    console.log(e.msj + " "+ e.error + ":" + e.data );
                }//function FAIL)
            );  
    }
    function setImages(data){
    
    
        $.each(data, function (index, datos) {
            var temp="../classes/imagen.php?img="+encodeURIComponent(datos['img'])+"&t="+((new Date).getTime());
            console.log(temp); // returns something like: ../classes/imagen.php?img=curso-2561.jpg&t=1489074434134
            $.ajax({
                url: temp,
                type: "GET",
                dataType: "image/jpg;base64",
                async:true,
              cache: false,
              success: function(datai){
                console.log(datai);
                    $('#pickimg').append('<img src="data:image/png;base64,' + datai + '" />');
              },
              fail: function(){
    
              }
            });
        });

最佳答案

The problem is that setImages() of my js, doesn't show the images

这是由于多种原因造成的:

  • PHP 代码实际上并未返回文件内容。为此,请使用类似 file_get_contents() 的函数, readfile()等等。此外,字符串应该是 base-64 编码的,所以使用 base64_encode() .

    $newimg=rand(1000 , 9999 );
    header("Content-Disposition: inline; fileimg= $newimg-$img");
    echo base64_encode(file_get_contents($path));
    exit();
    
  • 这对于第一个项目符号可能是多余的,但是 header Content-Disposition 的语法仅包含三个指令:namefilenamefilename* 1 。因此 fileimg 指令无效。该 header 可以包含文件名指令,但由于返回的是字符串,因此它是无用的:

    header("Content-Disposition: inline; filename=\"$newimg-$img\"");
    
  • 从这个意义上说,它并没有真正返回图像,因此 Content-Type 的 header 基本上是不正确的。因此,AJAX 调用(使用 $.ajax() )不应指定 dataType(即 dataType: "image/jpg;base64" ,无论如何它都不是动态的 - 对于 jpg、png 等)。因此,请删除该dataType选项。

查看 this phpFiddle 中应用的修改的演示。单击标记为 Run - F9 的按钮 - 然后当框架加载时,单击标记为 Update 的按钮以触发对 PHP 脚本的 AJAX 调用,该脚本将加载 PNG 图像并将其附加到 id 属性为“pickimg”的元素。

<小时/>

1 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#Directives

关于php - 通过 PHP 返回图像并使用 AJAX 设置为 src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42700042/

相关文章:

javascript - Bootstrap Navbar 在没有 JavaScript 的情况下展开/折叠移动设备

jquery - 如何在 css 列表中使用 jquery 交换类/id?

jquery - 如何通过 AJAX 到 HTTP 请求 JSON 来预填充 Web 表单?

jquery - 通过 JQuery 调用从服务器获取数据并加载到 DIV 中,无需刷新页面

php - 无法在 php 中回显 jquery(使用 ajax)变量

php - 未选择数据库 - php 和 phpmyadmin

php - 如何在查询中组合 RAND 和 DESC

php - 在mysql文件中加载数据在php脚本中不起作用

php - 与 PHP 的永久链接

javascript - 如何根据属性在类中的位置获取元素的具体名称