【问题标题】:How to use AJAX to download files without page referesh in Octobercms?Octobercms中如何使用AJAX下载文件而不刷新页面?
【发布时间】:2017-09-05 07:10:32
【问题描述】:

我是 laravel 和 october cms 的新手。我想添加一个按钮以允许用户下载 PDF 文件“a.pdf”,而无需指向新页面。我知道我必须使用 AJAX 并发送下载 http 响应以使浏览器显示“另存为...”对话框。到目前为止,这是我已经完成的:

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>

使用上面的代码我得到“文件“http://localhost/october/storage/app/media/a.pdf”不存在”错误。

我做错了什么?

【问题讨论】:

  • 希望您已创建文件夹位置并将文件放入该路径october/storage/app/media/a.pdfan?
  • 是的,我当然做到了!
  • 你能分享文件位置的绝对路径吗?
  • 我可以通过在浏览器中输入上述网址来下载文件。

标签: php ajax octobercms


【解决方案1】:

请将表头改为关联数组,

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

【讨论】:

  • 感谢您的回复。我尝试了您的解决方案,但仍然得到相同的结果。完整的错误是:
  • “文件“localhost/october/storage/app/media/a.pdf”不存在”在 E:\xampp\htdocs\october\vendor\symfony\http-foundation\File\File.php 的第 37 行
  • 你能分享完整的文件位置吗,比如/var/www/html/project/location/file.pdf
  • 我目前正在使用 XAMPP 在 Windows 上进行开发。我的文件存储在 E:\xampp\htdocs\october\storage\app\media\a.pdf 其中 XAMPP 的根从 E:\xampp\htdocs\ 运行
【解决方案2】:

对于任何可能觉得这很有用的人(这适用于通过媒体管理器上传的文件)。通过在我的布局代码 php 部分中添加 AJAX 处理程序来实现此功能。

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);
}

在页面和部分中添加了这个

{{ 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() }}

更新:对于通过后端使用插件 Octobercms 上传的文件会生成动态链接。要下载文件,只需创建一个前端组件。按照简易教程Watch + learn 创建一个简单的插件模型用于后端上传,Mastering components 创建一个准系统前端下载组件。获取文件详细信息后,只需使用简单的 href 即可下载文件。

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

帖子和附件的名称可以是任何取决于插件模型表单设计的名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多