【问题标题】:Unable to download file in laravel ajax on button click单击按钮时无法在laravel ajax中下载文件
【发布时间】:2020-11-09 07:12:36
【问题描述】:

当我尝试使用下载按钮在 laravel ajax 中下载文件时,它无法正常工作,我无法下载文件。

下面是我的代码:

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

控制器:

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);
    }

阿贾克斯:

$(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) {

                }
            });
        });

【问题讨论】:

  • 我看到你检索数据,它真的检索它但你需要知道在成功回调中执行的后续步骤吗?

标签: javascript jquery laravel


【解决方案1】:

只是为了相信您的数据会根据需要返回而对其进行伪编码,我认为您需要在成功回调中触发下载,并使用以下变体(可能需要根据您的需要进行调整):

$(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();
        }
    });
});

【讨论】:

    【解决方案2】:

    你可以传递header来强制文件类型和下载

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

    这里你需要根据你的文件类型添加标题

    参考链接https://laravel.com/docs/8.x/responses#file-downloads

    【讨论】:

    • 文件正在下载,但名称为 image.html
    • ($file_path, 'file.pdf', $headers) 这里第二个参数是名称,应该是正确的
    • $image_url= url('storage/documents/request/');$upload_report = $downloadReport->upload_report;返回 \Response::download($image_url, $upload_report, $headers);
    • 仍然获取 image.html
    • 是图片还是pdf?
    【解决方案3】:
     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 '';
        }
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 2011-02-07
    • 2016-05-10
    • 2019-04-29
    • 2018-04-06
    • 1970-01-01
    • 2014-10-16
    相关资源
    最近更新 更多