簡體   English   中英

從使用Ajax調用的php函數下載圖像

[英]Download image from a php function called with 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" );
  });
});

這將與將繼續發送的按鈕一起工作。單擊保存在var imagename中的id值,該ID值對應於保存在我的服務器上的圖像名。

這是將獲得該id的php函數:

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 . '">';

    }

那將在網絡響應中輸出圖像,但是我也會得到錯誤:

消息:mime_content_type():無效的路徑

但是,我要做的是單擊按鈕后就是從服務器下載該圖像。 我該怎么做? 謝謝!

mime_content_type()需要文件 ,而不是文件本身的數據。 像這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM