This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

Mr Hound
Mr Hound

I can't figure out how to get a database file attachment, to be downloaded with is real file name.

My model have many file attachements (many attachOne) and there is no problem to get link to them with

<a href="{{ model.myfile.path }}" target="_blank">{{ model.myfile.filename }}</a>

What I want to do is to get those files downloaded with their real file name.
I try to define an ajax event handler in my layout like so :

    function onDonwload()
    {
        $path = post('path');
        $name = post('name');

       // Storage::exists('uploads/public/5ce/28c/3aa/5ce27c3aae590316657518.pdf');     => OK
        // Storage::exists($path);   =>OK

        $path = storage_path().'/app/'. $path;
        return Response::download( $path, $name);
    }

and

<button data-request="onDonwload"   
  data-request-data="path: 'uploads/public/5ce/28c/3aa/5ce27c3aae590316657518.pdf', name: 'my real name">  
  Download  
</button>

No missing file error, but get the browser to freeze with an alert that say "A webpage slow down your browser, what do you want to do?".
¯\_(ツ)_/¯

Did I miss an important point?

Mr Hound
Mr Hound

I answer myself with an answer from Stackoverflow

  1. create page with /file-download/:id here you can specify any url wit param :id and give it name file-download you can give any name you like for demo i used this name.

  2. In that Page Html section will be Blank and in Page's code section add this code. here you can also check additional security check like user is logged in or not file is of related user or not. for now i am just checking file is related to particular Modal or not.

    function onStart() {
        $fileId = $this->param('id');
        $file = \System\Models\File::find($fileId);
        // for security please check attachment_type == your model with namespace
        // only then lat use download file other wise user can download all the files by just passing id
        if($file && $file->attachment_type == 'Backend\Models\User') { // here add your relation model name space for comparison
          $file->output('attachment');  
        }
        else {
          echo "Unauthorised.";
        }
        exit();
    }
  3. Generating links, please replace page name with page you created.

    <a href="{{ 'file-download'|page({'id': model.myfile.id}) }}" >{{ model.myfile.filename }}</a>

    Now, when you click on link file should be downloaded with its original name, and for invalid file id it should show message Unauthorised..

1-2 of 2

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.