风叶 2021-10-14 12:28:19 735次浏览 0条评论 0 0 0

Yii2 表单上传单个文件方法:

  1. 创建的模型文件
<?php
    namespace app\models;
    use Yii;
    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 $imageFile;

        /**
         * @return array the validation rules.
         */
        public function rules()
        {
            return [
                [['imageFile'], 'file'],
            ];
        }

        public function fileExists($uploadpath)
        {
            if(!file_exists($uploadpath)){
                mkdir($uploadpath);
            }
            return $uploadpath;
        }
    }
?>
  1. JS 前端视图文件
< div class="form-group">
    <label class="col-sm-2 control-label"><span class="text-danger">*&nbsp;</span>优美的图片:</label>
    <div class="col-sm-5" >
        <div class="ajaxUpload" id="upload_image" style="width: 216px;height:80px;background:url('<?=ImageSize::image(['url'=>$model->image,'width'=>216,'high'=>80])?>')">
            点击上传图片
        </div>
        只能上传jpg jpeg png格式,宽高比例 1080*400
        <div class="progress upload_progress">
            <div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
                <span class="sr-only"></span>
            </div>
            <input type="file" class="find_file"  id="find_file" style="visibility: hidden">
            <input type="button" class="upload_file" onclick="upload()" style="visibility: hidden">
        </div >
        <?=Html::activeInput('hidden',$model, 'image',['class'=>'form-control','id'=>'upload_image_input']) ?>
        <?=Html::error($model,'image',['class'=>'input_err'])?>
    </div >
</div >
  1. Ajax POST 异步上传方法
<script>
    $(function(){
        $("#upload_image").on('click',function () {
            $(".find_file").click();
        });
        $(".find_file").on('change',function () {
            $(".upload_file").click();
        });
    });
    function upload() {
        var formData = new FormData();//这里需要实例化一个FormData来进行文件上传
        formData.append("UploadForm[imageFile]",$("#find_file")[0].files[0]);
        $.ajax({
            type : "post",
            url : "/site/upload",
            data : formData,
            processData : false,
            contentType : false,
            success : function(flag){
                if (!flag) {
                    alert("文件上传失败!");
                }else{
                    $('#upload_image').css({'background':'url(./../uploads/977265aae12e32b2c4f5.jpg)'});
                    $('#upload_image_input').val(flag);
                }}
        });
    }
</script>
  1. 控制器文件 上传到当前项目同级的 uploads
 class SiteController extends BaseController
{
    public function actionUpload()
    {
        $model = new UploadForm();
        if (Yii::$app->request->isPost) {
            $model->imageFile = UploadedFile::getInstance($model, 'imageFile');
            if ($model->validate()) {
                $filePath = $model->fileExists(Yii::$app->basePath.'/uploads/');  //上传路径
                $extension = $model->imageFile->extension;
                $name = substr(md5($model->imageFile->baseName),1,20).strtotime('MHis',time());
                $url = $filePath. $name . '.' . $extension;
                $model->imageFile->saveAs($url);
                return $url;
            }
        }
        return false;
    }
}

成功完成 Yii2 异步文件上传

    没有找到数据。
您需要登录后才可以评论。登录 | 立即注册