您好,登錄后才能下訂單哦!
首先建立一個模型models/UploadForm.php,內容如下
namespace app\models; use yii\base\Model; use yii\web\UploadedFile; /** * UploadForm is the model behind the upload form. */ class UploadForm extends Model{ /** * @var UploadedFile file attribute */ public $file; /** * @return array the validation rules. */ public function rules() { return [ [['file'], 'file'], ]; } }
再建立一個視圖文件,內容如下
<style type="text/css"> .bar { width: 100%; height: 18px; background: green; } #sucess{ height: 18px;color: #d76f01; font-weight: 12px;display: none;} </style> <div id="sucess">上傳成功</div> <input type="file" name="UploadForm[file]" id="fileupload_input"/> <div id="progress" > <div class="bar" ></div> </div> <script src="<?php echo \common\CommFun::base_url() ?>statics/saas/scm/app2_release/js/common/plugins/fileupload/js/vendor/jquery.ui.widget.js"></script> <script src="<?php echo \common\CommFun::base_url() ?>statics/saas/scm/app2_release/js/common/plugins/fileupload/js/jquery.iframe-transport.js"></script> <script src="<?php echo \common\CommFun::base_url() ?>statics/saas/scm/app2_release/js/common/plugins/fileupload/js/jquery.fileupload.js"></script> <script type="text/javascript"> $(function () { $("#fileupload_input").fileupload({ url: "index.php?r=bill/include",//文件上傳地址,當然也可以直接寫在input的data-url屬性內 formData: {param1: "p1", param2: "p2"},//如果需要額外添加參數可以在這里添加 done: function (e, result) { //done方法就是上傳完畢的回調函數,其他回調函數可以自行查看api //注意result要和jquery的ajax的data參數區分,這個對象包含了整個請求信息 //返回的數據在result.result中,假設我們服務器返回了一個json對象 if (JSON.stringify(result.result) == '"200"') { //alert('上傳成功') } else { alert(JSON.stringify(result.result)) } }, progressall: function (e, data) {//設置上傳進度事件的回調函數 var progress = parseInt(data.loaded / data.total * 100); $('#progress .bar').css( 'width', progress + '%' ); if(progress==100){ $('#sucess').show() } } }) }); </script>
最后建立控制器文件,內容如下
//獲取新單據號 public function actionInclude(){ $model = new UploadForm(); if (Yii::$app->request->isPost) { $model->file = UploadedFile::getInstance($model, 'file'); $allow = array('xls','xlsx'); if ($model->file && in_array($model->file->extension,$allow)) { $result = $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension); if($result){ echo '200'; exit; }else{ echo '上傳失敗'; exit; } }else{ echo '格式不對'; exit; } } return $this->render('includeView', ['model' => $model]); }
YII2上傳:http://www.yiichina.com/tutorial/328
fileupload:http://bbs.9ria.com/thread-245293-1-1.html
http://www.jq22.com/jquery-info230
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。