从使用ajax调用的php函数中下载图像

时间:2022-07-24 16:04:44

I have this ajax:

我有这个ajax:

 $('.getid').on('click', function(){
        var imagename =  $(this).data("id");
        // you can make ajax call here to get data
        $.ajax({
        type: "POST",
        url: "Monitor/downloadDesiredImage",
        data: {'val' : imagename},
        dataType: "text"
        }).done(function(data) {
       console.log(data);        
       }).fail(function() {
    alert( "error" );
  });
});

This will work with a button that will send on.click a id value saved in a var imagename, that is a string that correspond to a image name saved on my server.

这将与一个将发送的按钮一起工作。单击保存在var imagename中的id值,这是与保存在我的服务器上的图像名称对应的字符串。

This is the php function that will get that id :

这个php函数会得到id:

public function downloadDesiredImage() {
        $imagename = $_POST['val'];
        echo "this is my ".  $imagename;
        $file = file_get_contents('./images/'.$imagename.'.jpg', FILE_USE_INCLUDE_PATH);
        $imageData = base64_encode(($file));
        $src = 'data: '.mime_content_type($file).';base64,'.$imageData;
        echo '<img src="' . $src . '">';

    }

That will output the image in the network response, but I will also get the error :

它会在网络响应中输出图像,但我也会得到误差:

Message: mime_content_type(): Invalid path

信息:mime_content_type():无效的路径

But what I want to do is after I click the button is to download that image from my server. How I can do that ? Thanks!

但是我要做的是在我点击按钮后从我的服务器上下载图像。我怎么做呢?谢谢!

1 个解决方案

#1


2  

mime_content_type() expects the file name, not the data of the file itself. Something like this:

mime_content_type()需要文件名,而不是文件本身的数据。是这样的:

mime_content_type('./images/'.$imagename.'.jpg')

#1


2  

mime_content_type() expects the file name, not the data of the file itself. Something like this:

mime_content_type()需要文件名,而不是文件本身的数据。是这样的:

mime_content_type('./images/'.$imagename.'.jpg')