weixin_33713503 2018-06-14 07:14 采纳率: 0%
浏览 89

通过ajax成功下载文件

I have a function that record a row in database everytime when someone download a file. I have modal, first user import user information - name, phone, country i ec... after this the button for download is active and he can download it ... how to download file with ajax? if render success and in console show content of file, but do not download it ... here is button:

<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>

here is a ajax function:

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

and the public function in controller:

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
";
            $headers .= "Content-type: text/html; charset=utf-8
";
            $headers .= "From: " . $companyInfo->email . "
";
            $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);
}
}

i tried with $result variable and with return the file, but not working with both methods ...

  • 写回答

2条回答 默认 最新

  • 三生石@ 2018-06-14 07:56
    关注

    You can't download file by AJAX because JavaScript cannot save files directly to a user's computer

    For More please refer this:

    Download a file by jQuery.Ajax

    评论

报告相同问题?

悬赏问题

  • ¥20 qtcreat 使用msvc编译器开发软件运行时字体锯齿感严重
  • ¥15 c#直接使用C++ 写的class 后续
  • ¥15 为何显示keyerror fruit
  • ¥15 关于#stm32#的问题:/* User can add his own implementation to report the HAL error return state */
  • ¥15 imageware粗糙度表面
  • ¥15 python使用pulp线性优化时报错
  • ¥15 为什么我的uibot导入py模块出错呀。py文件放在了uibot里对应的python文件夹了,卸了重安也不行
  • ¥15 开源或低价数据中台哪个最好
  • ¥15 arduino编程出现字符串疑似覆盖现象
  • ¥15 我的b站在没有碰到屏幕的情况下偶尔会自动跳出进度条,就像在屏幕上点了一下一样,但我并没有点。而且视频进度并没有变。这可能是什么原因造成的?