dongshi9407 2019-02-03 15:12
浏览 565

Laravel在Ajax模式中调用response() - > file($ pathToFile)

Since I dont like the default way a file is presented to a user when "return response()->file($pathToFile);" is called I wanted to make a Version in which a file isnt direcly displayed in the current Tab of the Website but rather in a popup Modal - Kind of like how its done when you preview a file in Dropbox.

So what I did is add a button to my view that calls for my Route "preview_modal" This Route then calls my "preview_modal" method in my FileController. This Method returns the requested File in the Modal.

But sadly when the Mimetype of the requested File is not a "text/*" type of File I get this kind of Text presented to me in my Modal:

�PNG  IHDRq�:sRGB���gAMA���a pHYs���o�d   *IDATx^��r�6��~ Ob~��jn9�-��.Q�v˖-��ʥ��`ip���L��d��?�E����'0�0�M�afİ�3Ì6q�a��&�03b���aF����L&�V���H|�̏t[���kȲ�01����,�|�r�b��`����㙮�|:��/���� r/[X�>`�]��KH���5�Oޟa� ��N�A�|��KX��2�:γ�d ٢��,�

In this case it was a PNG that was beeing opened. This Text was just a little example.

I have no idea what im looking at If anyone knows what this is i would greatly appreciate it. The "return response()->file()" works fine for the same file if it isnt called inside the ajax modal.


<button data-path="{{ route('files.preview_modal', $file) }}" class="button is-info load-ajax-modal" role="button" data-toggle="modal" data-target="#dynamic-modal">Preview</button>

Ajax Call:

    headers: {
        'X-CSRF-Token': $('meta[name="_token"]').attr('content')

$('.load-ajax-modal').click(function () {
        type: 'GET',
        url: $(this).data('path'),

        success: function (result) {
            $('#dynamic-modal div.modal-body').html(result);


Route::get('preview_modal/{file}', 'FileController@preview_modal')->name('files.preview_modal');

preview_modal Method:

public function preview_modal(File $file)
  return response()->file(storage_path("$file->path"));
  • 写回答

4条回答 默认 最新

  • douqiao1997 2019-02-03 18:29

    Try final these 2 solutions

    1. storage_path("$file->path") remove double quotes: storage_path($file->path)

    because you are using variable not the string

    1. may be you should convert you image to base64.

      $path = storage_path($file->path); $type = pathinfo($path, PATHINFO_EXTENSION); $data = file_get_contents($path); $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

    and then use it in html enjoy the day mate :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 ajax服务器不能下载
  • ¥15 运用c++和opencv实现二维码的识别和三维坐标的建立
  • ¥15 k210烧入flash报错error:2005
  • ¥15 GIS土地利用预测FLUS模型
  • ¥15 visual studio code打不出来中文双引号
  • ¥20 关于#matlab#的问题:ps:完美符合要求有打赏(相关搜索:自适应)
  • ¥15 声音感应灯,问题出在哪里
  • ¥15 关于#matlab#的问题:(0,0)上的贝塞尔曲线,0)上的贝塞尔曲线,并使用自适应积分计算其从t=0到不大于1的任意值区间的弧长
  • ¥20 关于#r语言#rda分析作图的问题,请各位专家解答!
  • ¥50 找回 股票行情系统的资源问题