0

I was wondering if it is possible to create a file and instantiate a download in an async call, started with jQuery? This is my jQuery:

try{
            var templatePath = evt.currentTarget.parentElement.parentElement.childNodes[2].innerText;
            var url = "?q=myApp/api/myClass/";
            $.ajax({
                url: url,
                type: 'get',
                data: { methodName:'downloadTemplate', templatePath: templatePath },
                beforeSend: function(xhr ){

                    });
                },
                success: function(data) {    
                   //handle success
                },
                error: function() {
                    //handle error
                }
            });
        }catch(ex){
            //handle error             
        }

and my PHP:

private function downloadTemplate($templatePath){
        try{
            $downloadPath = substr($_SERVER['DOCUMENT_ROOT'],0,-1). $GLOBALS['base_path'] .  self::FILE_UPLOAD_PATH ."/";
            $currentPos = strrpos($templatePath, '/');
            $strLength = strlen($templatePath);
            $templatePath = substr($templatePath, $currentPos + 1, $strLength);
            $fullPath = $downloadPath . $templatePath;

            if (file_exists($fullPath)) {
                $content = file_get_contents($fullPath);
                $content = iconv( 'UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $content );

                header("Content-Type: application/DOC; charset=UTF-8;");
                header("Cache-Control: public");
                header("Content-Description: File Transfer");
                header("Content-Disposition: attachment; filename=download.DOC");
                header("Content-Transfer-Encoding: binary");

                echo $content;
                exit();    
            } else {
                throw new Exception("Template does not exist: " . $templatePath);
            }


        }catch (Exception $ex){
            throw $ex;
        }
    }

This doesnt create a download, though. All it does is complete the request and write the contents to the HTTP response. Is there any way to accomplish this? I don't even care if I have to create a full post back, if it can be done in the PHP function.

thanks jason

jason
  • 3,821
  • 10
  • 63
  • 120
  • You can look into html blobs but the browser support are not that good. https://developer.mozilla.org/en-US/docs/Web/API/Blob – Jesper Blaase May 06 '14 at 11:14
  • In general, this is not possible. What you'd need to do is: Have a server side action create a file and store it at a temporary location, then return a URL to that location to your AJAX call. On the client-side, you can then redirect/open a new window to that URL, which initiates the actual download. – lethal-guitar May 06 '14 at 11:34

0 Answers0