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

    评论
  • weixin_33724059 2018-06-14 08:26
    关注

    You can do this: 1) add a empty a href tag in form:

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

    2) in controller change url path to file:

    $result['file'] = $file;
    

    3) add this to your ajax function:

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

    this will simulate a click and the file will be automatic download

    评论

报告相同问题?

悬赏问题

  • ¥80 关于海信电视聚好看安装应用的问题
  • ¥15 vue引入sdk后的回调问题
  • ¥15 求一个智能家居控制的代码
  • ¥15 ad软件 pcb布线pcb规则约束编辑器where the object matpcb布线pcb规则约束编辑器where the object matchs怎么没有+15v只有no net
  • ¥15 虚拟机vmnet8 nat模式可以ping通主机,主机也能ping通虚拟机,但是vmnet8一直未识别怎么解决,其次诊断结果就是默认网关不可用
  • ¥20 求各位能用我能理解的话回答超级简单的一些问题
  • ¥15 yolov5双目识别输出坐标代码报错
  • ¥15 这个代码有什么语法错误
  • ¥15 给予STM32按键中断与串口通信
  • ¥15 使用QT实现can通信