XF 2.2 Returning a File to the User and Implementing AJAX Form Action

DKGE

Member
Hey

I was wondering and struggling all day on how to make XenForo return a file to the user after a request.
I managed to get it working on direct url access. /xxxx/download
PHP:
public function actionDownload(ParameterBag $params)
    {
        $visitor = \XF::visitor();

        // Check if the user is logged in
        if (!$visitor->user_id) {
            return $this->error('You must be logged in to download scripts.');
        }

        $client = \XF::app()->http()->client();
        $url = 'https://xxxx/api/v1/download?s=' . $params['id'] . '&u=' . $visitor->user_id;

        try {
            $response = $client->get($url, [
                'headers' => [
                    'User-Agent' => 'XF2 Addon'
                ]
            ]);
            $fileContent = $response->getBody()->getContents();
        } catch (\GuzzleHttp\Exception\ClientException $e) {
            if ($e->getResponse()->getStatusCode() == 403) {
                return $this->error('You do not have permission to download this file.');
            } else {
                return $this->error('An error occurred while downloading the file.');
            }
        }

        if (empty($fileContent)) {
            return $this->error('File not found');
        }

        // Extract the file name from the Content-Disposition header
        $fileName = '';
        $headers = $response->getHeaders();
        if (isset($headers['Content-Disposition'][0])) {
            preg_match('/filename="([^"]+)"/', $headers['Content-Disposition'][0], $matches);
            if (isset($matches[1])) {
                $fileName = $matches[1];
            }
        }

        // Set the appropriate headers for file download
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        header('Content-Length: ' . strlen($fileContent));

        echo $fileContent;
        exit();
    }

But now i would love to be able to access this though a ajax form action so you get a nice confirmation message and don't go to a different page.
PHP:
return $this->message('Downloading ' . $fileName . '...');

What might I be missing or doing wrong?
 
Back
Top Bottom