当前位置: 首页 > 知识库问答 >
问题:

在进度条中显示"单个文件上传失败"错误消息

宗政卓
2023-03-14

这是我的代码格式。php:

<?php $form = ActiveForm::begin(); ?>
<?php
echo FileInput::widget([
    'name' => 'file_uploads',
    'language' => 'id',
    'options' => [
        'accept' => 'doc/*', 'file/*',
        'multiple' => true,
        'enableLabel' => true,
    ],
    'pluginOptions' => [
        'allowedFileExtensions' => ['xls', 'xlsx'],
        'uploadUrl' => Url::to(['/pib/pib-data/create']),
        'maxFileSize' => 1024,
        'maxFileCount' => 1,
        'showCaption' => false,
        'showMessage'=>false,
        'purifyHtml'=>false
    ]
]);
?>
<?php ActiveForm::end(); ?>

这是我在控制器中使用的代码:

<?php
public function actionCreate() {
    $model = new PibData();
    $connection = \Yii::$app->db;
    $userId = Yii::$app->user->id;
    if (Yii::$app->user->isGuest) {
        return $this->redirect(['/site/login']);
    }

    $sqlHeader = "UPDATE pib_data SET is_exported = '1' WHERE user_id = '$userId'";
    $exeQuery = Yii::$app->db->createCommand($sqlHeader)->execute();
    $date = new DateTime('now', new \DateTimeZone('Asia/Jakarta'));
    $created_at = $date->format('Y:m:d H:i:s');
    $dirTrash = Yii::getAlias('@webroot/trash');
    $dirSubTrash = Yii::getAlias('@webroot/trash/trash_pib');

    if (!is_dir($dirTrash)) {
        mkdir(Yii::getAlias('@webroot/trash'));
        if (!is_dir($dirSubTrash)) {
            mkdir(Yii::getAlias('@webroot/trash/trash_pib'));
        }
    } else {
        if (!is_dir($dirSubTrash)) {
            mkdir(Yii::getAlias('@webroot/trash/trash_pib'));
        }
    }

    if (Yii::$app->request->post()) {
        $file = UploadedFile::getInstancesByName('file_uploads');
        $middleName = substr(md5(microtime() * 100000), rand(0, 9), 5);
        if ($file !== null) {
            $name = $userId . '_' . $middleName . '_' . date('Y-m-d') . '_' . $file[0]->getBaseName() . "." . $file[0]->getExtension();
            $pathproduct = Yii::getAlias('@webroot/trash/trash_pib/') . $name;
            $file[0]->saveAs($pathproduct);
        Yii::$app->response->format = Response::FORMAT_JSON;
        return [];
        } else {
            $error[] = "Silahkan pilih terlebih dahulu file" . "<strong>" . " Excel " . "</strong>" . "yang akan di convert.";
            Yii::$app->session->setFlash('error', $error);
            return $this->render('create', ['model' => $model]);
        }

        $modelUser = Users::find()->where(['id' => $userId])->one();
        $parentId = $modelUser->parent_id;

        $objPHPExcel = new \PHPExcel();
        $fileName = Yii::getAlias('@webroot/trash/trash_pib/') . $name;
        $inputFiles = fopen(Yii::getAlias('@webroot/trash/trash_pib/') . $name, "r");
        try {
            $inputFileType = \PHPExcel_IOFactory::identify($fileName);
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($fileName);
        } catch (Exception $ex) {
            die('Error');
        }

        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestDataRow();
        $highestColumn = $sheet->getHighestDataColumn();
        $colNumber = PHPExcel_Cell::columnIndexFromString($highestColumn);
        $col = $colNumber - 1;
        $arrayData = [];
        
        for ($row = 1; $row <= $highestRow; ++$row) {
            $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
            $arrayData[] = array_map(function($values) {
                $tempArray = [];
                foreach ($values as $key => $value) {
                    $newKey = $key + 1;
                    $tempArray[] = $newKey . '_' . $value;
                }
                return $tempArray;
            }, $rowData);
        }

        $arrayHeader = array_shift($arrayData);
        $countArrayData = count($arrayData);
        $countArrayHeader = count($arrayHeader[0]);

        for ($i = 0; $i < $countArrayData; $i++) {
            for ($j = 0; $j < $countArrayHeader; $j++) {
                if ($j < 9) {
                    $finalData[$i][] = substr($arrayData[$i][0][$j], 2);
                } else {
                    $finalData[$i][] = substr($arrayData[$i][0][$j], 3);
                }
            }
        }

        for ($x = 0; $x < $countArrayData; $x++) {
            array_unshift($finalData[$x], "dummy");
        }

        $tempData = mysql_escape_string(json_encode($finalData));
        $tempHeader = json_encode($arrayHeader);
        $header = base64_encode($tempHeader);

        $command_1 = "DELETE FROM pib_json_data WHERE user_id= '$userId'";
        $query_1 = Yii::$app->db->createCommand($command_1)->execute();
        $command_2 = "INSERT INTO pib_json_data(json_data, user_id, created_at) VALUES('$tempData', '$userId', '$created_at')";
        $query_2 = Yii::$app->db->createCommand($command_2)->execute();

        $_SESSION['header'] = $header;
        $_SESSION['validHeader'] = 'validHeader';

        return Yii::$app->response->redirect(['/pib/pib-header/select-header']);
    } else {
        return $this->render('create', [
                    'model' => $model,
        ]);
    }
}
?>

任何帮助都将受到感激。

谢谢

共有1个答案

景凌
2023-03-14

良好的...根据留档,在“重要”部分:

您必须从服务器发送有效的JSON响应,否则上载过程将失败。即使没有遇到任何错误,也必须至少从服务器发送一个空的JSON对象{}。

所以,我相信你的代码应该是这样的。

控制器:

<?php
public function actionCreate() {
    $model = new PibData();
    $connection = \Yii::$app->db;
    $userId = Yii::$app->user->id;
    if (Yii::$app->user->isGuest) {
        return $this->redirect(['/site/login']);
    }

    $sqlHeader = "UPDATE pib_data SET is_exported = '1' WHERE user_id = '$userId'";
    $exeQuery = Yii::$app->db->createCommand($sqlHeader)->execute();
    $date = new DateTime('now', new \DateTimeZone('Asia/Jakarta'));
    $created_at = $date->format('Y:m:d H:i:s');
    $dirTrash = Yii::getAlias('@webroot/trash');
    $dirSubTrash = Yii::getAlias('@webroot/trash/trash_pib');

    if (!is_dir($dirTrash)) {
        mkdir(Yii::getAlias('@webroot/trash'));
        if (!is_dir($dirSubTrash)) {
            mkdir(Yii::getAlias('@webroot/trash/trash_pib'));
        }
    } else {
        if (!is_dir($dirSubTrash)) {
            mkdir(Yii::getAlias('@webroot/trash/trash_pib'));
        }
    }

    if (Yii::$app->request->post()) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $result = [];
        $file = UploadedFile::getInstancesByName('file_uploads');
        $middleName = substr(md5(microtime() * 100000), rand(0, 9), 5);
        if ($file !== null) {
            $name = $userId . '_' . $middleName . '_' . date('Y-m-d') . '_' . $file[0]->getBaseName() . "." . $file[0]->getExtension();
            $pathproduct = Yii::getAlias('@webroot/trash/trash_pib/') . $name;
            $file[0]->saveAs($pathproduct);
        } else {
            $error[] = "Silahkan pilih terlebih dahulu file" . "<strong>" . " Excel " . "</strong>" . "yang akan di convert.";
            //Yii::$app->session->setFlash('error', $error);
            //return $this->render('create', ['model' => $model]);
            $result = [
                'error' => $error
            ]; // change error notification used Kartik FileInput build-in error message 
        }

        $modelUser = Users::find()->where(['id' => $userId])->one();
        $parentId = $modelUser->parent_id;

        $objPHPExcel = new \PHPExcel();
        $fileName = Yii::getAlias('@webroot/trash/trash_pib/') . $name;
        $inputFiles = fopen(Yii::getAlias('@webroot/trash/trash_pib/') . $name, "r");
        try {
            $inputFileType = \PHPExcel_IOFactory::identify($fileName);
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($fileName);
        } catch (Exception $ex) {
            //die('Error');
            $result = [
                'error' => $ex
            ]; // change error notification used Kartik FileInput build-in error message 
        }

        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestDataRow();
        $highestColumn = $sheet->getHighestDataColumn();
        $colNumber = PHPExcel_Cell::columnIndexFromString($highestColumn);
        $col = $colNumber - 1;
        $arrayData = [];

        for ($row = 1; $row <= $highestRow; ++$row) {
            $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
            $arrayData[] = array_map(function($values) {
                $tempArray = [];
                foreach ($values as $key => $value) {
                    $newKey = $key + 1;
                    $tempArray[] = $newKey . '_' . $value;
                }
                return $tempArray;
            }, $rowData);
        }

        $arrayHeader = array_shift($arrayData);
        $countArrayData = count($arrayData);
        $countArrayHeader = count($arrayHeader[0]);

        for ($i = 0; $i < $countArrayData; $i++) {
            for ($j = 0; $j < $countArrayHeader; $j++) {
                if ($j < 9) {
                    $finalData[$i][] = substr($arrayData[$i][0][$j], 2);
                } else {
                    $finalData[$i][] = substr($arrayData[$i][0][$j], 3);
                }
            }
        }

        for ($x = 0; $x < $countArrayData; $x++) {
            array_unshift($finalData[$x], "dummy");
        }

        $tempData = mysql_escape_string(json_encode($finalData));
        $tempHeader = json_encode($arrayHeader);
        $header = base64_encode($tempHeader);

        $command_1 = "DELETE FROM pib_json_data WHERE user_id= '$userId'";
        $query_1 = Yii::$app->db->createCommand($command_1)->execute();
        $command_2 = "INSERT INTO pib_json_data(json_data, user_id, created_at) VALUES('$tempData', '$userId', '$created_at')";
        $query_2 = Yii::$app->db->createCommand($command_2)->execute();

        $_SESSION['header'] = $header;
        $_SESSION['validHeader'] = 'validHeader';

        //return Yii::$app->response->redirect(['/pib/pib-header/select-header']);
        $result = [
            'url' => Url::to(['/pib/pib-header/select-header'])
        ]; // return url variable to be used by jquery
        return $result;
    } else {
        return $this->render('create', [
                    'model' => $model,
        ]);
    }
}
?>

视图:

<?php

use yii\web\View;
...

<?php $form = ActiveForm::begin(); ?>
<?php
echo FileInput::widget([
    'name' => 'file_uploads',
    'language' => 'id',
    'options' => [
        'accept' => 'doc/*', 'file/*',
        'multiple' => true,
        'enableLabel' => true,
    ],
    'pluginOptions' => [
        'allowedFileExtensions' => ['xls', 'xlsx'],
        'uploadUrl' => Url::to(['/pib/pib-data/create']),
        'maxFileSize' => 1024,
        'maxFileCount' => 1,
        'showCaption' => false,
        'showMessage'=>false,
        'purifyHtml'=>false
    ]
]);
?>
<?php ActiveForm::end(); ?>

<?php
$this->registerJS("
    $('#input-id').on('fileuploaded', function(event, data, previewId, index) { // replace input-id with your file input id
        var response = data.response;
        $(location).attr('href', response.url); // redirect use jquery
    });", View::POS_END);

希望能有所帮助。

快乐编码:)

 类似资料:
  • 本文向大家介绍原生JS上传大文件显示进度条 php上传文件代码,包括了原生JS上传大文件显示进度条 php上传文件代码的使用技巧和注意事项,需要的朋友参考一下 JS原生上传大文件显示进度条,php上传文件,供大家参考,具体内容如下 在php.ini修改需要的大小: upload_max_filesize = 8M    post_max_size = 10M    memory_limit = 2

  • 问题内容: 我有上传表格,允许用户上传多个文件。我决定,如果文件很大,则进度条会很好。下面是我的源代码。我是jQuery的新手,通常我只会使用php,但是我发现ajax更加用户友好。 图像上传正常,数组发送到ajax,但进度条不动。实际上,调用这两个函数的console.log都不会产生这种情况。有没有正确的方法来调用我的ajax请求中的函数,以使此进度条正常工作。 beforeSubmit:be

  • 本文向大家介绍Jquery和BigFileUpload实现大文件上传及进度条显示,包括了Jquery和BigFileUpload实现大文件上传及进度条显示的使用技巧和注意事项,需要的朋友参考一下 实现方法:用到了高山来客 的bigfileupload组件,用高山来客的方法,弹出一个模式窗口,然后不停刷新获取进度,始终觉得体验感不好,于是想到用jquery来实现无刷新进度显示,因为提交页面后, 不能

  • 在添加poi-ooxml的依赖项时,我的pom文件显示错误 从https://repo.maven.apache.org/maven2中传输org.apache.xmlbeans:xmlbeans:jar:2.6.0失败,已缓存在本地存储库中,在经过central的更新间隔或强制更新之前,不会重新尝试解决方案。原始错误:无法将工件org.apache.xmlbeans:xmlbeans:jar:2

  • 问题内容: 好的,这样我就可以使用Java FTP上传文件,我想更新标签和进度条。用百分比文本标签,用百分比int值标记。现在,使用当前代码,在上传结束时只能获得100和完整条。在上传过程中,它们均未更改。 这里是: 问题答案: 从它的声音(并且没有任何证据可以证明主观)看来,您在事件调度线程中处理一个耗时的动作 您可能想阅读Swing中的并发性以获得更多了解 我建议使用SwingWorker进行

  • 本文向大家介绍带有多个进度条的HTML5文件上传,包括了带有多个进度条的HTML5文件上传的使用技巧和注意事项,需要的朋友参考一下 为了使其正常工作,您需要解决xhr progress事件,该事件在所有列表项都已创建后就会触发。 该XHR 应该知道你想做什么-