简体   繁体   中英

Unable to download file in laravel ajax on button click

When I am trying to use the download button to download file in laravel ajax, it is not working properly and I am not able to download file.

Below is my code:

<button type="button" request_id="'.$data->id.'" class="btn btn-success download_request_btn" > Download </button>';

Controller:

public function downloadReport(Request $request)
    {
        $request_id = $request->request_id;
        $downloadReport = Upload::where('id', $request_id)->first();
        $upload_report = $downloadReport->upload_report;
        $headers = array(
            'Content-Type: application/pdf',
            'Content-Type: application/docx',
          );
        $url= url('storage/documents/request/'. $upload_report);
        return response()->download($url);
    }

Ajax:

$(document).on('click', '.download_request_btn', function(){
            var request_id = $(this).attr('request_id');
           console.log(request_id);
           var formData = new FormData();
            formData.append('request_id',request_id);
            jQuery.ajax({
                type: "post",
                url: site_url+"/DownloadAjax",
                data: formData,
                contentType:false,
                processData:false,
                success: function (res) {

                }
            });
        });

you can pass header to force file type and download

$file_path = storage_path('documents/request/'. $upload_report);
$headers = array('Content-Type'=> 'application/pdf');
return \Response::download($file_path, 'file.pdf', $headers);

here you need to add header based on your file type

ref link https://laravel.com/docs/8.x/responses#file-downloads

Just to pseudo-code it up with trusting your data is coming back as desired I think you need to trigger the download in your success callback with a variation of the following (may need to adjust to your need):

$(document).on('click', '.download_request_btn', function(){
    var request_id = $(this).attr('request_id');
    console.log(request_id);
    var formData = new FormData();
    formData.append('request_id',request_id);
    jQuery.ajax({
        type: "post",
        url: site_url+"/DownloadAjax",
        data: formData,
        contentType:false,
        processData:false,
        success: function (res) {
            const data = res;
            const link = document.createElement('a');
            link.setAttribute('href', data);
            link.setAttribute('download', 'yourfilename.extensionType'); // Need to modify filename ...
            link.click();
        }
    });
});
 if(!empty($fileName) && file_exists(($exportDir.'/'.$fileName))) {
            $data = route('yourdownloadCSV',['nameFile' => $fileName]);
        }

        return response()->json([
            'status' => 1,
            'data'   => $data,
            'message'=> trans('messages.item_upload_shop_ok'),
        ]);

public function yourdownloadCSV($nameFile) {
        ini_set('memory_limit', '9072M');
        ini_set('MAX_EXECUTION_TIME', '-1');
        set_time_limit(10*60);

        $fullFolderZipFile  = public_path().'/export/'.date('ym');
        $filePath           = $fullFolderZipFile.'/'.$nameFile;
        $nameDownload       = "test";

        if(file_exists($filePath)) {
            $byteS  = filesize($filePath);
            $mb     = number_format($byteS / 1048576, 2) ;
            if($mb>10){
                $filePathZip= ZipUtil::generateZipFromFile($filePath,$fullFolderZipFile,$nameFile);
                $nameDownload .=".zip";
            }else{
                $filePathZip = $filePath;
                $nameDownload .=".".pathinfo($nameFile, PATHINFO_EXTENSION);
            }

            $mimeType = File::mimeType($filePathZip);
            return response()->download($filePathZip,$nameDownload,[
                'Content-Type' => $mimeType,
                'Content-Encoding' => 'Shift-JIS'
            ])->deleteFileAfterSend(true);
        }
        return '';
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM