[Vuejs]-How can i force download files with Vue + Laravel

0👍

With laravel, you can write function download. Maybe

$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url);

Example file download is docx file then content-type is mime of docx => application/vnd.openxmlformats-officedocument.wordprocessingml.document

With vue, you can use axios to download file.

0👍

I use this code that it downloads any files.(you must customize it for your need):

for vuejs component:

axios.get( 'user/getTicketFile', {
        params: { 
          number: this.$route.params.id,
          name: item
         }, 
          responseType: 'blob'
        })
        .then(function (r) 
        {
          const url = window.URL.createObjectURL(new Blob([r.data]));
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', 'file.'+r.headers.ext); //or any other extension
          document.body.appendChild(link);
          link.click();

          //hide loader
          i.loader = false
      });

    },

and this is laravel backend function sample:

public function getTicketFile(Request $request)
    {
        $number = $request['number'];
        $name = $request['name'];
        
        $filePath = storage_path( 'app/tickets/'.$number.'/'.$name );

        if( file_exists($filePath) )
        {
            $headers = array(
                'ext' => pathinfo($name, PATHINFO_EXTENSION),
            );
            return response()->download($filePath, '', $headers);
        }
    }
}

Leave a comment