csv批量更新操作

产品大佬,商品数据的更新,处理系统商品id或商品货号其一必填之外,其他字段都可以让客户不填;坑是真的多;首先csv对php来说;如果用户不填需要使用这样子才是可以判断的if ($v[24] === '' || $v[24] === NULL) {};因为不填和填0判断的php写法是不一样的。

原理场景说明:使用了多台服务器;批量更新的时候如果csv表数据很大,发现部分数据会更新失败的;因为csv文件是由客户上传到某台服务器上的;而我们的更新根据的就是那个csv文件的内容;因为考虑把csv的数据存入redis缓存;还有个问题就是如果前端的csv文件太大,nginx服务器会报错504;因此考虑使用前端分页上传csv,每次上传缓存起来。

后台php代码控制器方法:  

public function actionBatchUpdate()
{
    set_time_limit(0);
    if (\Yii::$app->request->isPost) {
        $file = \Yii::$app->request->post();
        if (!$file['url']) {
            return [
                'code' => 1,
                'msg' => '请输入模板地址'
            ];
        }
        $fileName = $file['url'];
        //将文件一次性全部读出来
        $excelData = $insertRows = [];
        $content = str_replace("\n,,", '', trim(file_get_contents($fileName)));
        $excelData = explode("\n", $content);
        unset($excelData[0]);
        $key = md5($fileName);//缓存key
        $page = isset($file['page']) ? $file['page'] : 0;
        $count = \Yii::$app->cache->get($key. 'count'); //判断缓存标识
        //文件存在并且没有缓存则设置缓存
        if (!empty($excelData) && empty($count)) {
            $chunkData = array_chunk($excelData , 200);  //200个做一个记录对象
            $count = count($chunkData);
            if ($count > 30) {
                return [
                    'code' => 1,
                    'msg' => '允许导入最大限制数为6000条,导入失败,请筛选数据后重新导入。'
                ];
            }
            for ($i=0; $i<$count; $i++) {
                \Yii::$app->cache->set($key. $i, $chunkData[$i]);   //设置csv分批使用多键缓存
            }
            \Yii::$app->cache->set($key. 'count', $count, 3600);  //设置缓存标识
        }
        if ($page == $count || $count == 1) {
            \Yii::$app->cache->delete($key. 'count');  //删除缓存标识
        }
        $data = \Yii::$app->cache->get($key. $page);   //判断缓存csv数据是否存在
        foreach($data as $value){                   //这里的方式会存在bug;请看我的另一篇博文!!!!!!!!!!!!
            $string = mb_convert_encoding(trim(strip_tags(str_replace('"', '', $value))), 'utf-8', 'gbk');//转码
            $v = explode(',', trim($string));        
            $insertRows[] = $v;
        }
        \Yii::$app->cache->delete($key. $page);  //删除缓存csv数据缓存键
        $form = new GoodsInsertForm();  //限制属性传送
        $form->store_id = $this->store->id;
        $form->plugin = get_plugin_type();
        $data = $form->batchUpdate($insertRows);
        $data['page'] = $page;
        $data['count'] = $count === false ? 1 : $count;
        return [
            'code' => 0,
            'msg' => '操作成功',
            'data' => $data,
        ];
    }
    return $this->render('batch-update', [
    ]);
}

更新代码:

 /**
     * Created by Mr.DJ.
     * description: 批量更新商品库存和价格
     */
    public function batchUpdate($arrCSV)
    {
        $goodsId = [];//序号
        $goodsEmpty = [];  //商品货号是否存在
        $catEmpty = [];   //分类
        $drug_typeEmpty = [];//药物类型
        $nameEmpty = [];    //商品名称
        $sub_titleEmpty = []; //商品副标题
        $unitEmpty = [];    //单位
        $sortEmpty = [];    //排序
        $virtual_salesEmpty = [];  //虚拟数量
        $confine_countEmpty = [];   //限购数量
        $weightEmpty = [];    //重量
        $priceEmpty = [];     //售价
        $cost_priceEmpty = [];   //成本价
        $original_priceEmpty = [];     //原价
        $serviceEmpty = [];     //服务内容
        $freightEmpty = [];     //运费设置
        $piecesEmpty = [];   //单品满件包邮
        $foreheadEmpty = [];   //单品满额包邮
        $is_negotiableEmpty = [];   //是否开启面议
        $appr_numberEmpty = [];   //国药准字
        $specEmpty = [];   //规格
        $factory_nameEmpty = [];   //生产厂家
        $is_levelEmpty = [];   //是否享受会员折扣
        $giveEmpty = [];   //积分赠送
        $integralforeheadEmpty = [];   //积分抵扣
        $integralmoreEmpty = [];   //允许多件累计折扣
        $individual_shareEmpty = [];   //是否开启单独推广设置,暂时默认不开启
        $share_commission_firstEmpty = [];   //一级佣金
        $share_commission_secondEmpty = [];   //二级佣金
        $share_commission_thirdEmpty = [];   //三级佣金
        $quick_purchaseEmpty = [];   //是否添加到快速购买 ,TODO热销
        $hot_cakesEmpty = [];       //快速购买中热销1,0非
        $detailEmpty = [];   //图文详情
        $share_typeEmpty = [];   //佣金类型 0百分比 1固定佣金
        $stockEmpty = [];   //导入数量
        $error = [];   //操作失败
        $type = $this->plugin ?: 0;
        $key = -1;
        $successCount = $errorCount = 0;

        $drug_type_arr = ['处方药' => 1, '红色非处方药' => 2, '绿色非处方药' => 3, '非药物' => 4];
        $is_user = ['是' => 1, '否' => 0, '' => 0];
        $_tuiguang = ['是' => 1, '否' => 0, '' => 0];
        $_quick_buy = ['是' => 1, '否' => 0, '' => 0];
        $_hot_cake = ['是' => 1, '否' => 0, '' => 0];
        $_is_duojian = ['是' => 1, '否' => 0, '' => 0];
        $_guiguang_persent = ['0' => 0, '1' => 1, '' => 0];
        //门店数量
        $shop_max_count = Admin::findOne(['id' => $this->store->admin_id])->shop_max_count;
        //运输设置
        $postageRiles = array_column(PostageRules::find()->where(['store_id' => $this->store->id, 'is_delete' => 0])->asArray()->all(), 'id', 'name');
        //$postageRiles[count($postageRiles)]=['默认' => 0];
        // print_r($postageRiles);die();
        //商户拥有分类
        $store_cat = array_column(Cat::find()->where(['store_id' => $this->store->id, 'is_delete' => 0])->asArray()->all(), 'id', 'name');
        //该商户门店列表
        $shop = Shop::find()->where(['store_id' => $this->store_id, 'is_delete' => 0])->asArray()->all();
        $shop_list = array_column($shop, 'id');
        foreach ($arrCSV as $v) {
            $key++;
            $goodsId[] = $v[0];  //序号ID
            $goodsEmpty[] = $v[1];  //货号
            $catEmpty[] = $v[2];   //分类
            $drug_typeEmpty[] = $v[3];//药物类型
            $nameEmpty[] = $v[4];    //商品名称
            $sub_titleEmpty[] = $v[5]; //商品副标题
            $unitEmpty[] = $v[6];    //单位
            $sortEmpty[] = $v[7];    //排序
            $virtual_salesEmpty[] = $v[8];  //虚拟数量
            $confine_countEmpty[] = $v[9];   //限购数量
            $weightEmpty[] = $v[10];    //重量
            $priceEmpty[] = $v[11];     //售价
            $cost_priceEmpty[] = $v[12];   //成本价
            $original_priceEmpty[] = $v[13];     //原价
            $serviceEmpty[] = $v[14];     //服务内容
            $freightEmpty[] = $v[15];     //运费设置
            $piecesEmpty[] = $v[16];   //单品满件包邮
            $foreheadEmpty[] = $v[17];   //单品满额包邮
            $appr_numberEmpty[] = $v[18];   //国药准字
            $specEmpty[] = $v[19];   //规格
            $factory_nameEmpty[] = $v[20];   //生产厂家
            $is_levelEmpty[] = $v[21];   //是否享受会员折扣
            $giveEmpty[] = $v[22];   //积分赠送
            $integralforeheadEmpty[] = $v[23];   //积分抵扣
            $integralmoreEmpty[] = $v[24];   //允许多件累计折扣
            $individual_shareEmpty[] = $v[26];   //是否开启单独推广设置,暂时默认不开启
            $share_typeEmpty[] = $v[27];  //开启单独推广设置,0为百分比,1为固定佣金
            $share_commission_firstEmpty[] = $v[28];   //一级佣金
            $share_commission_secondEmpty[] = $v[29];   //二级佣金
            $share_commission_thirdEmpty[] = $v[30];   //三级佣金
            $quick_purchaseEmpty[] = $v[31];   //是否添加到快速购买 ,TODO热销
            $hot_cakesEmpty[] = $v[32];   //是添加到快速购买中,热销1,非热销0
            $detailEmpty[] = $v[33];   //图文详情
            $stockEmpty[] = $v[34];  //导入数量
            $error[$key];

            if (empty($v[0]) && empty($v[1])) {
                $error[$key] = '商品ID和商品货号不能为空';
                $errorCount += 1;
                continue;
            }

            $goodsModel = Goods::find()->where([
                'store_id' => $this->store_id,
                'is_delete' => 0,
                'mch_id' => 0,
                'type' => $type
            ]);
            if (!empty($v[0])) {
                $goods = $goodsModel->andWhere(
                    ['id' => $v[0]]
                )->one();
                if (!$goods) {
                    $error[$key] = '商品ID不存在';
                    $errorCount += 1;
                    continue;
                }
            }
            if (!empty($v[1]) && empty($v[0])) {
                $goods = $goodsModel->andWhere(
                    ['like', 'attr', '"no":"' . $v[1] . '"',]
                )->one();
                if (!$goods) {
                    $error[$key] = '商品货号不存在';
                    $errorCount += 1;
                    continue;
                }
            }
            $data1 = json_decode($goods['full_cut'], true);
            $data = json_decode($goods['integral'], true);

            if (empty($v[25])) {
                $v[25] = $data['more'];
            }
            if (!array_key_exists(trim($v[2]), $store_cat)) {
                $error[$key] = '该分类不存在';
                $errorCount += 1;
                continue;
            }

            if (empty($v[3]) || !array_key_exists(trim($v[3]), $drug_type_arr) || (trim($v[3]) == '处方药' && (empty($v[19]) || empty($v[20]) || empty($v[21])))) {
                $error[$key] = '药物类型不能为空,当是处方药:国药准字,规格,生产厂家均不能为空';
                $errorCount += 1;
                continue;
            }

            if (!empty($v[15])) {
                if (!array_key_exists($v[15], $postageRiles)) {
                    $error[$key] = '该商户无该运费设置';
                    $errorCount += 1;
                    continue;
                }
            }
//            if (!is_numeric($v[11])) {
//                $error[$key] = '售价不正确';
//                $errorCount += 1;
//                continue;
//            }
            if (!array_key_exists($v[22], $is_user)) {
                $error[$key] = '是否享受会员折扣,只能填是或否或不填';
                $errorCount += 1;
                continue;
            }
            if (!array_key_exists(trim($v[25]), $_is_duojian)) {
                $error[$key] = '是否允许多件累计抵扣,只能填是或否';
                $errorCount += 1;
                continue;
            }
            if (!array_key_exists($v[26], $_tuiguang)) {
                $error[$key] = '是否开启单独推广设置,只能填是或否';
                $errorCount += 1;
                continue;
            }

            if (!empty($v[31]) && !array_key_exists($v[31], $_quick_buy)) {
                $error[$key] = '是否开启快速购买,只能填是或否';
                $errorCount += 1;
                continue;
            }
            if (!empty($v[27]) && !array_key_exists($v[27], $_guiguang_persent)) {
                $error[$key] = '开启单独推广之后,只能填0或1';
                $errorCount += 1;
                continue;
            }
            if (!empty($v[31]) && !array_key_exists($v[31], $_hot_cake)) {
                $error[$key] = '是否热销,只能填是或否';
                $errorCount += 1;
                continue;
            }
            if (!empty($v[13]) && !is_numeric($v[13]) || intval($v[13])<0) {
                $error[$key] = '原价不能为空';
                $errorCount += 1;
                continue;
            }
            if (!empty($v[12]) && !is_numeric($v[12]) || intval($v[12])<0) {
                $error[$key] = '成本价不能为空';
                $errorCount += 1;
                continue;
            }
            if (($_tuiguang[$v[26]] == 1 && ($v[27] != '0' && $v[27] != '1')) && ($v[27] == '1' && (empty($v[28]) || empty($v[29]) || empty($v[30])))) {
                $error[$key] = '开启佣金,推广类型不正确;一,二,三级的佣金必须设置';
                $errorCount += 1;
                continue;
            }
            //区分商品、砍价商品
            $v[26] = !empty($v[26]) ? $_tuiguang[$v[26]] : '';
            $v[31] = !empty($v[31]) ? $_quick_buy[$v[31]] : '';
            $v[32] = !empty($v[32]) ? $_hot_cake[$v[23]] : '';
            $v[25] = !empty($v[25]) ? $_is_duojian[$v[25]] : '';
            if ($v[24] === '' || $v[24] === NULL) {
                $v[24] = $data['forehead'];
            }
            if ($v[16] === '' || $v[16] === NULL) {
                $v[16] = $data1['pieces'];
            }
            if ($v[17] === '' || $v[17] === NULL) {
                $v[17] = $data1['forehead'];
            }
            if ($v[23] === '' || $v[23] === NULL) {
                $v[23] = $data['give'];
            }
            if ($v[2] === '' || $v[2] === NULL) {
                $v[2] = $goods['cat_id'];
            }
            if ($v[4] === '' || $v[4] === NULL) {
                $v[4] = $goods['name'];
            }
            if ($v[5] === '' || $v[5] === NULL) {
                $v[5] = $goods['sub_title'];
            }
            if ($v[14] === '' || $v[14] === NULL) {
                $v[14] = $goods['service'];
            }
            if ($v[19] === '' || $v[19] === NULL) {
                $v[19] = $goods['appr_number'];
            }
            if ($v[20] === '' || $v[20] === NULL) {
                $v[20] = $goods['spec'];
            }
            if ($v[21] === '' || $v[21] === NULL) {
                $v[21] = $goods['factory_name'];
            }
            if ($v[33] === '' || $v[33] === NULL) {
                $v[33] = $goods['detail'];
            }

            if ($v[6] === '' || $v[6] === NULL) {
                $v[6] = $goods['unit'];
            }
            if ($v[7] === '' || $v[7] === NULL) {
                $v[7] = $goods['sort'];
            }
            if ($v[8] === '' || $v[8] === NULL) {
                $v[8] = $goods['virtual_sales'];
            }
            if ($v[9] === '' || $v[9] === NULL) {
                $v[9] = $goods['confine_count'];
            }
            if ($v[10] === '' || $v[10] === NULL) {
                $v[10] = $goods['weight'];
            }
            if ($v[11] === '' || $v[11] === NULL) {
                $v[11] = $goods['price'];
            }
            if ($v[12] === '' || $v[12] === NULL) {
                $v[12] = $goods['cost_price'];
            }
            if ($v[13] === '' || $v[13] === NULL) {
                $v[13] = $goods['original_price'];
            }

            if ($v[27] === '' || $v[27] === NULL) {
                $v[27] = $goods['share_type'];
            }
            if ($v[28] === '' || $v[28] === NULL) {
                $v[28] = $goods['share_commission_first'];
            }
            if ($v[29] === '' || $v[29] === NULL) {
                $v[29] = $goods['share_commission_second'];
            }
            if ($v[30] === '' || $v[30] === NULL) {
                $v[30] = $goods['share_commission_third'];
            }

            if ($v[26] === '' || $v[26] === NULL) {
                $v[26] = $goods['individual_share'];
            }
            if ($v[31] === '' || $v[31] === NULL) {
                $v[31] = $goods['quick_purchase'];
            }
            if ($v[32] === '' || $v[32] === NULL) {
                $v[32] = $goods['hot_cakes'];
            }

            $t = \Yii::$app->db->beginTransaction();
            $catId = empty($v[2]) ? $goods['cat_id'] : $store_cat[$v[2]];
            $cateInfo = GoodsCat::find()->where(['goods_id' => $goods['id'], 'is_delete' => 0])->select('cat_id')->asArray()->all();
            $cateInfo = array_column($cateInfo, 'cat_id', 'id');
            if ($cateInfo && !in_array($catId, $cateInfo)) {
                $cateInfo = new GoodsCat();
                $cateInfo->store_id = $goods['store_id'];
                $cateInfo->goods_id = $goods['id'];
                $cateInfo->cat_id = $catId;
                $cateInfo->addtime = time();
                $cateInfo->save();
            }

            $res = \Yii::$app->db->createCommand()->update('xcxmall_goods',
                [
                    'store_id' => $this->store_id,
                    'drug_type' => empty($drug_type_arr[$v[3]]) ? $goods['cat_id'] : $drug_type_arr[$v[3]],
                    'name' => empty($v[4]) ? $goods['name'] : $v[4],
                    'sub_title' => empty($v[5]) ? $goods['sub_title'] : $v[5],
                    'unit' => $v[6],
                    'sort' => $v[7],
                    'virtual_sales' => $v[8],
                    'confine_count' => $v[9],
                    'weight' => $v[10],
                    'price' => $v[11],
                    'cost_price' => $v[12],
                    'original_price' => $v[13],
                    'service' => empty($v[14]) ? $goods['service'] : $v[14],
                    'freight' => empty($postageRiles[$v[15]]) ? $goods['freight'] : $postageRiles[$v[15]],
                    'appr_number' => empty($v[19]) ? $goods['appr_number'] : $v[19],
                    'spec' => empty($v[20]) ? $goods['spec'] : $v[20],
                    'factory_name' => empty($v[21]) ? $goods['factory_name'] : $v[21],
                    'is_level' => empty($is_user[$v[22]]) ? $goods['is_level'] : $is_user[$v[22]],
                    'full_cut' => '{"pieces":"' . $v[16] . '","forehead":"' . $v[17] . '"}',
                    'integral' => '{"give":"' . $v[23] . '","forehead":"' . $v[24] . '","more":"' . $v[25] . '"}',
                    'individual_share' => $v[26],
                    'share_type' => $v[27],
                    'share_commission_first' => $v[28],
                    'share_commission_second' => $v[29],
                    'share_commission_third' => $v[30],
                    'quick_purchase' => $v[31],
                    'hot_cakes' => $v[32],
                    'detail' => empty($v[33]) ? $goods['detail'] : $v[33],
                    'goods_num' => empty($v[34]) ? 0 : $v[34],
                    'is_negotiable' => 0,//不开启面议
                    'addtime' => time(),
                ],
                ['id' => $goods['id']]
            )->execute();
            try {
                if (!$res) {
                    $t->rollBack();
                    $error[$key] = '更新失败,或原数据未更改';
                    $errorCount += 1;
                } else {
                    $data_new = [];
                    //数字限制
                    if (is_numeric($v[34]) && $v[34]>=0) {
                        $data_new['stock'] = $v[34];
                    }
                    if (trim($v[11])>=0) {
                        $data_new['price'] = $v[11];
                    }
                    if ($data_new) {
                        //print_r('11');die();
                        Inventory::updateAll($data_new, ['goods_id' => $goods['id'], 'store_id' => $this->store->id]);
                        $successCount += 1;
                        $t->commit();
                    }
                }
            } catch (\Exception $e) {
                return $this->getErrors();
            }

        }
        $data = [];
        $max = max(
            count($goodsEmpty),
            count($catEmpty),
            count($drug_typeEmpty),
            count($nameEmpty),
            count($sub_titleEmpty),
            count($unitEmpty),
            count($sortEmpty),
            count($virtual_salesEmpty),
            count($confine_countEmpty),
            count($weightEmpty),
            count($priceEmpty),
            count($cost_priceEmpty),
            count($original_priceEmpty),
            count($serviceEmpty),
            count($freightEmpty),
            count($piecesEmpty),
            count($foreheadEmpty),
            count($is_negotiableEmpty),
            count($appr_numberEmpty),
            count($specEmpty),
            count($factory_nameEmpty),
            count($is_levelEmpty),
            count($giveEmpty),
            count($integralforeheadEmpty),
            count($integralmoreEmpty),
            count($individual_shareEmpty),
            count($share_commission_firstEmpty),
            count($share_commission_secondEmpty),
            count($share_commission_thirdEmpty),
            count($quick_purchaseEmpty),
            count($hot_cakesEmpty),
            count($detailEmpty),
            count($stockEmpty),
            count($error)
        );

        for ($i = 0, $k = 0; $i < $max; $k++, $i++) {
            if ($error[$k]) {
                $data[$k][] = $goodsEmpty[$k];
                $data[$k][] = $error[$k];
            }
        }
        return [
            'data' => empty($data) ? [0] : array_merge($data),
            'success_count' => $successCount,
            'error_count' => $errorCount
        ];
    }

前端代码:

<?php
defined('YII_ENV') or exit('Access Denied');
//2020年4月14日14:51:32
use yii\widgets\LinkPager;
use yii\widgets\ActiveForm;

$urlManager = Yii::$app->urlManager;
$urlStr = get_plugin_url();
$this->title = '批量更新商品信息';
?>

<div class="panel mb-3" id="app">
    <div class="panel-header"><?= $this->title ?></div>
    <div class="panel-body">
        <form class="auto-form" method="post" v-if="form_list==''">
            <div class="form-group row">
                <div class="form-group-label col-sm-2 text-right">
                    <label class="col-form-label">批量更新导入模板</label>
                </div>
                <div class="col-sm-4">
                    <div class="csv-picker" data-url="<?= $urlManager->createUrl(['upload/temp-file']) ?>">
                        <div class="input-group">
                            <input class="csv-picker-input csv form-control" name="url"
                                   placeholder="请输入模板地址">
                            <a href="javascript:" class="btn btn-secondary csv-picker-btn">选择批量模板</a>
                        </div>

                        <div class="csv-preview"></div>
                    </div>
                </div>
            </div>

            <div class="form-group row">
                <div class="form-group-label col-sm-2 text-right">
                </div>
                <div class="col-sm-6">
                    <a class="btn btn-primary auto-file-btn" href="javascript:">确认批量更新导入</a>
                    <a class="btn btn-primary hide-status-btn" href="<?= $urlManager->createUrl([$urlStr . '/update-model']) ?>" >默认格式下载</a>
                </div>
            </div>
            <div class="form-group row">
                <div class="form-group-label col-sm-2 text-right">
                </div>
                <div class="col-sm-6" style="color: red;">
                    一次最多6千条数据(导入时间需要20分钟),如超过6千条,请分次导入!<br>
                    <div class="alert alert-danger rounded-0">
                        注意事项<br>
                        1.可以通过商品ID或者货号更新商品信息;<br>
                        2.只需填写更新的字段,其他留空即可;<br>
                        3.库存字段是更新所有门店的库存,请慎重操作<br>
                        4.数据输入请勿有空格tab,请按照下载模板输入<br>
                    </div>
                </div>
            </div>
        </form>
        <div v-if="form_list!=''">
            <div class="form-group">更新成功&nbsp;<strong>{{success_count}}</strong>&nbsp;条</div>
            <div class="form-group">更新失败&nbsp;<strong style="color: red;">{{error_count}}</strong>&nbsp;条</div>
            <table class="table table-bordered bg-white">
                <thead >
                <tr>
                    <th>商品货号</th>
                    <th>更新失败原因</th>
                </tr>
                </thead>
                <col style="width: 25%">
                <col style="width: 25%">
                <tbody>

                <tr v-for="(item,index) in form_list">
                    <td class="nowrap">{{item[0]}}</td>
                    <td class="nowrap">{{item[1]}}</td>
                </tr>

                </tbody>
            </table>
        </div>
    </div>
</div>

<script type="text/javascript">
    var app = new Vue({
        el: "#app",
        data: {
            form_list: [],
            success_count: [],
            error_count: [],
        }
    });

    $(document).on('click', '.auto-form .auto-file-btn', function () {
        var form = $(this).parents('.auto-form');
        submit(form);
        return false;
    });

    function submit(form) {
        var btn = $(form.find('.auto-file-btn'));
        btn.btnLoading(btn.text());
        var data = form.serialize();
        $.ajax({
            url: form.attr('action') || '',
            type: form.attr('method') || 'get',
            dataType: 'json',
            data: data,
            success: function (res) {
                if(res.code==0){
                    if (res.data.count == 1) {
                        btn.btnReset();
                        app.form_list = res.data.data;
                        app.success_count = res.data.success_count;
                        app.error_count = res.data.error_count;
                        $.alert({
                            content: res.msg,
                        });
                    }else{
                        forsubmit(res, data, form.attr('action'));
                    }
                }else{
                    btn.btnReset();
                    $.alert({
                        content: res.msg,
                    });
                }
            },
            error: function (e) {
                btn.btnReset();
                $.alert({
                    title: '<span class="text-danger">系统错误</span>',
                    content: e.responseText,
                });
            }
        });
    };

    function forsubmit(resdata, data, url) {
        var a = resdata.data.data;
        var error_count = resdata.data.error_count;
        var success_count = resdata.data.success_count;
        data += '&page=' + (parseInt(resdata.data.page) + 1);
        var ab = data;
        $.ajax({
            url: url,
            type: 'post',
            dataType: 'json',
            data: data,
            success: function (res) {
                error_count += res.data.error_count;
                success_count += res.data.success_count;
                if (res.data.data[0]) {
                    a.push.apply(a,res.data.data);
                }
                res.data.success_count = success_count;
                res.data.error_count = error_count;
                res.data.data = a;
                if(res.code == 0){
                    if (res.data.page == res.data.count) {
                        app.form_list = a;
                        app.success_count = success_count;
                        app.error_count = error_count;
                        $.alert({
                            content: res.msg,
                        });
                    }else{
                        forsubmit(res, ab);
                    }
                };
            },
            error: function (e) {
                btn.btnReset();
                $.alert({
                    title: '<span class="text-danger">系统错误</span>',
                    content: e.responseText,
                });
            }
        });

    };

    // Custom example logic
    $(document).ready(function () {
        var csv_picker = $('.csv-picker');
        csv_picker.each(function (i) {
            var picker = this;
            var el = $(this);
            var btn = el.find('.csv-picker-btn');
            var url = el.data('url');
            var input = el.find('.csv-picker-input');
            var view = el.find('.csv-preview');

            function uploaderCsv() {

                var el_id = $.randomString(32);
                btn.attr("id", el_id);

                var uploader = new plupload.Uploader({
                    runtimes: 'html5,flash,silverlight,html4',
                    browse_button: el_id, // you can pass an id...
                    url: url,
                    flash_swf_url: '<?=$statics?>/mch/js/Moxie.swf',
                    silverlight_xap_url: '<?=$statics?>/mch/js/Moxie.xap',

                    filters: {
                        max_file_size: '50mb',
                        mime_types: [
                            {title: "files", extensions: "csv"}
                        ]
                    },

                    init: {
                        PostInit: function () {
                        },
                        FilesAdded: function (up, files) {
                            $('.form-error').hide();
                            uploader.start();
                            btn.btnLoading("正在上传");
                            uploader.disableBrowse(true);

                            plupload.each(files, function (file) {
                                console.log(file)
                                view.html('<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>');
                            });
                        },
                        FileUploaded: function (uploader, file, responseObject) {
                            if (responseObject.status == undefined || responseObject.status != 200) {
                                return true;
                            }
                            var res = $.parseJSON(responseObject.response);
                            if (res.code != 0) {
                                $('.form-error').html(res.msg).show();
                                return true;
                            }
                            $(input).val(res.data.url);
                            $('.csv-check').prop('href', res.data.url);
                            $('.csv-preview').find('span').html('100%');
                        },

                        UploadProgress: function (up, file) {
                            var percent = file.percent - 1;
                            $($("#" + file.id).find('b')[0]).html('<span>' + percent + "%</span>");
                        },

                        Error: function (up, err) {
                            console.log(err,11);
                            if(err.code=='-601'){
                                $.alert({
                                    title: '<span class="text-danger">上传失败</span>',
                                    content: '文件扩展错误',
                                });
                            }
                        },
                        UploadComplete: function (uploader, files) {
                            btn.btnReset();
                            uploader.destroy();
                            uploaderCsv();
                        }
                    }
                });
                uploader.init();
            }

            uploaderCsv();
        });
    });
    $(document).on('change', '.csv', function () {
        $('.csv-check').attr('href', this.value);
    });
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值