简体   繁体   中英

How to use AJAX to download files without page referesh in Octobercms?

I am new to laravel and october cms. I want to add a button to allow users download a PDF file, 'a.pdf', without directing to a new page. I know that I have to use AJAX and send a download http response in order to make browsers show a 'Save As...' dialog box. So far this is what I have accomplished:

title = "Sandbox"
url = "/test"
layout = "default"
==
<?php
function onDownload()
{
    $pathToFile = Url::to("/storage/app/media/a.pdf");
    $fileName = "download.pdf";
    $headers = [
        'HTTP/1.1 200 OK',
        'Pragma: public',
        'Content-Type: application/pdf'
    ];
    return Response::download($pathToFile, $fileName, $headers);
}
?>
==
<div class="container">
    <form class="form-inline" data-request="onDownload">
        <button type="submit" class="btn btn-primary" data-attach-loading>Download</button>
    </form>
</div>

I get "The file " http://localhost/october/storage/app/media/a.pdf " does not exist" error using above code.

What am I doing wrong?

Please change the header into associative array,

$headers = array(
                 'Content-Type'=>'application/pdf',
           );

For any who may find this useful ( This works for files uploaded via media manager ). Got this working by adding the AJAX handler in my layout code php section.

function onDownloadButtonClicked(){

    $pathToFile = base_path('storage/app/media/path/actual filename here');
    $fileName = "filename shown on download here";
    $headers = [
        'HTTP/1.1 200 OK',
        'Pragma: public',
        'Content-Type: application/pdf'
    ];
    return Response::download($pathToFile, $fileName, $headers);
}

Added this on the pages and partials

{{ form_open({ request: 'onDownloadButtonClicked' }) }}
<button type="submit" class="tg-btn tg-btnicon" data-attach-loading>
    <i class="fa fa-file-pdf-o"></i> Download Here
</button>
{{ form_close() }}

Update : For file uploaded via the backend using a plugin Octobercms generates dynamic links. To download the files just create a frontend component. Follow easy tutorial Watch + learn to create a simple plugin model for backend uploading and Mastering components for a barebones frontend download component. Once the file details are acquired a simple href will do for file download.

<a href="{{ post.attachment.path }}"
            download="{{ post.attachment.file_name }}"><i class="fa fa-download"></i> &nbsp Download File</a>

The names posts and attachment could be anything depending plugin model form design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM