通过ajax成功下载文件

时间:2018-06-14 07:14:04

标签: jquery ajax yii2

我有一个函数,每当有人下载​​文件时,都会在数据库中记录一行。我有模态,第一个用户导入用户信息 - 名称,电话,国家我...在此之后下载的按钮是活动的,他可以下载它...如何下载文件与ajax? 如果渲染成功并在控制台中显示文件内容,但不要下载它... 这是按钮:

<div class="col-md-10 col-xs-12 broshura" >
    <a class="popupBroshura-trigger">
       <div class="col-md-3 col-xs-3 pr0 pull-left  pt15"><img src="/images/download.png" /></div>
       <div class="col-md-9 col-xs-9 pl0 pull-left">
          <div id="six" class="button customBtn pl0"><?=Yii::$app->OutData->getLabel(281);?></div>
       </div>
   </a>
</div>

这是一个ajax函数:

 function downloadGallery() {
        var product_id = $('input[name="product_id"]').val();
        var names = $('input[name="StatisticBroshura[names]"]').val();
        var email = $('input[name="StatisticBroshura[email]"]').val();
        var firma = $('input[name="StatisticBroshura[firma]"]').val();
        var phone = $('input[name="StatisticBroshura[phone]"]').val();
        var flag = $('input[name="flag"]').val();
        var country = $('input[name="StatisticBroshura[country]"]').val();
        var captcha_code = $('input[name="StatisticBroshura[captcha_code]"]').val();
        var container = $('#hidden-result');
        $.ajax({
            method: 'post',
            url: '/admin/site/downloadbroshura',
            data :{
                product_id: product_id,
                names: names,
                firma: firma,
                country: country,
                phone: phone,
                flag: flag,
                email: email,
                captcha_code: captcha_code
            },
            success: function ( data ) {
                var data = JSON.parse( data );
                if(data['result'] == true){
                    if(data [ 'flag' ] == 1) {
                        $('input[name="StatisticBroshura[email]"]').val('');
                        $('input[name="StatisticBroshura[names]"]').val('');
                        $('input[name="StatisticBroshura[firma]"]').val('');
                        $('input[name="StatisticBroshura[country]"]').val('');
                        $('input[name="StatisticBroshura[phone]"]').val('');
                        $('input[name="StatisticBroshura[captcha_code]"]').val('');
                        $('.message-broshura').html(data['textError']);
                        $('.message-broshura').css('border', '2px solid');
                        $('html, body').animate({
                            scrollTop: $(".popupRequest").offset().top
                        }, 2000);
                        window.location.href = data [ 'file' ];
                    }else{
                        $('.message-broshura').html(data['textError']);
                        $('.message-broshura').css('border', '2px solid');
                        $('.message-broshura').css('color', 'cornflowerblue!important');
                        $('html, body').animate({
                            scrollTop: $(".popupBroshura").offset().top
                        }, 2000);

                    }
                }

                return false;
            }
        });
    }

和控制器中的公共功能:

public function actionDownloadbroshura()
{
 if (isset($_POST['product_id']) and !empty($_POST['product_id'])) {
 $result['result'] = true;
        $result['textError'] = '';
        $result['flag'] = '';
        $result['file'] = '';
        $flag = $_POST['flag'];
        $class = '';
        $first_step = Yii::$app->getRequest()->getQueryParam('first_step');
        $second_step = Yii::$app->getRequest()->getQueryParam('second_step');
        $product_step = Yii::$app->getRequest()->getQueryParam('product');
        $last = explode('-', $product_step);
        $id = end($last);
        $lastparent = explode('-', $second_step);
        $idparent = end($lastparent);
        $product = Product::findOne($id);
        $modelBroshura = new StatisticBroshura();
        $messageBroshura = "";
        $sessionBroshura = new Session;
        $sessionBroshura->open();
        $model = new Request();
        $message = '';

        if (session_status() == PHP_SESSION_NONE) {
            session_start();
        }
        if ($_SESSION['captcha']['code'] != $_POST['captcha_code']) {
            $result['textError'] = Label::findOne(65)->label;
            $result['flag'] = 2;
        } else {
            $result['textError'] = Label::findOne(310)->label;
            $result['flag'] = 1;
            $companyInfo = CompanyInfo::findOne(1);
            $headers = "MIME-Version: 1.0\r\n";
            $headers .= "Content-type: text/html; charset=utf-8\r\n";
            $headers .= "From: " . $companyInfo->email . "\r\n";
            $messageAdmin = "";
            $product = Product::findOne($_POST['product_id']);
            $modelBroshura = new StatisticBroshura();
            $file = $product->getBroshuraDownload($product->id);
            if (isset($file) && $modelBroshura->save()) {
                if (isset($_POST['StatisticBroshura'])) {
                    $request_broshura = new StatisticBroshura();
                    $request_broshura->names = $_POST['names'];
                    $request_broshura->firma = $_POST['firma'];
                    $request_broshura->email = $_POST['email'];
                    $request_broshura->phone = $_POST['phone'];
                    $request_broshura->country = $_POST['country'];
                    $request_broshura->product_id = $_POST['product_id'];
                    $request_broshura->save(false);
                }
            }

            $messageBroshura = Label::findOne(306)->label;
            $messageAdmin .= "<div style=\"width: 800px;\"><center><a href=\"http://" . $_SERVER['SERVER_NAME'] . "\"><img src='http://" . $_SERVER['SERVER_NAME'] . "/images/logo-header.png' alt=\"OPTIXCO\" /></a></center><h1><center>Изтеглена е брошура от : " . $_POST['email'] . "!</center></h1>";
            $messageAdmin .= "<table width=\"800px\" style=\"border-collapse: collapse; border: 1px solid black; margin-bottom: 30px;\">";
            $messageAdmin .= "<tr style=\"background-color: #ddd; border: 1px solid black;\"><td colspan=\"2\"><h2><center>Информация на потребителя: </center></h2></td></tr>";
            $messageAdmin .= "<tr style=\"border: 1px solid black;\"><td style=\"border: 1px solid black;\">Имена: </td><td style=\"border: 1px solid black;\">" . $_POST['names'] . "</td></tr>";
            $messageAdmin .= "<tr style=\"border: 1px solid black;\"><td style=\"border: 1px solid black;\">Имейл: </td><td style=\"border: 1px solid black;\">" . $_POST['email'] . "</td></tr>";
            $messageAdmin .= "<tr style=\"border: 1px solid black;\"><td style=\"border: 1px solid black;\">Телефон: </td><td style=\"border: 1px solid black;\">" . $_POST['phone'] . "</td></tr>";
            $messageAdmin .= "<tr style=\"border: 1px solid black;\"><td style=\"border: 1px solid black;\">Държава: </td><td style=\"border: 1px solid black;\">" . $_POST['country'] . "</td></tr>";
            $messageAdmin .= "<tr style=\"border: 1px solid black;\"><td style=\"border: 1px solid black;\">Фирма/Организация: </td><td style=\"border: 1px solid black;\">" . $_POST['firma'] . "</td></tr>";
            $messageAdmin .= "<tr style=\"border: 1px solid black;\"><td style=\"border: 1px solid black;\">Брошура за продукт: </td><td style=\"border: 1px solid black;\">" . $product->title . "</td></tr>";
            $messageAdmin .= "</table></div>";

            @mail($companyInfo->email2, "Изтегляне на брошура - " . $_SERVER['SERVER_NAME'], $messageAdmin, $headers);

            $result['file'] = Yii::$app->response->sendFile(Yii::getAlias('@frontend/web') . $file);
        }
        echo json_encode($result);
}
}

我尝试使用$ result变量并返回文件,但不使用这两种方法......

2 个答案:

答案 0 :(得分:1)

您无法通过AJAX下载文件 因为JavaScript无法将文件直接保存到用户的计算机

如需了解更多信息,请参阅:

Download a file by jQuery.Ajax

答案 1 :(得分:1)

你可以这样做: 1)在表单中添加一个空的href标记:

<a id="download-broshura" name="download-file" download> </a>

2)在控制器中更改url路径到文件:

$result['file'] = $file;

3)将此添加到你的ajax函数:

document.getElementById('download-broshura').click();

这将模拟点击,文件将自动下载