2017-08-22 17:44:04 3163次浏览 5条回答 1 悬赏 10 金钱

微信截图_20170822174255.png

正在学习yii2.0高级版,现在遇到文件上传的问题,如图,怎么把这个输入框弄成logo上传,求大神帮忙,谢谢

  • 回答于 2017-08-22 20:15 举报

    视图:
    <?php
    use yii\widgets\ActiveForm;
    use yii\helpers\Html;
    ?>
    <?php $form=ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data'],'action'=>['upload/file'],'method'=>'post',])?>
    <?=$form->field($model,'file[]')->fileInput(['multiple'=>true])?>
    <?php echo Html::submitButton('提交',['class' => 'btn btn-primary'])?>
    <?php ActiveForm::end();?>

  • 回答于 2017-08-23 16:19 举报

    现在yii有很多vender资源去找下,下载的资源,或者你可以写个原生,或者yii的上传,文档中有

  • 回答于 2017-08-24 09:28 举报

    /**

     * 
     * @param string|array $uploadedFile 输入框名称 或者 [model,attribute]
     * @param type $directory
     * @return JsonResponse
     * @throws ApiException
     */
    public function uploadOne($uploadedFile, $directory = '')
    {
        try {
            if ($directory) {
                $this->uploadDir .= DIRECTORY_SEPARATOR . $directory;
            }
            if (is_string($uploadedFile)) {
                $upload = UploadedFile::getInstanceByName($uploadedFile);
                $name = $uploadedFile;
            } else if (is_array($uploadedFile) && isset($uploadedFile['model']) && isset($uploadedFile['attribute'])) {
                $upload = UploadedFile::getInstance($uploadedFile['model'], $uploadedFile['attribute']);
                $name = $uploadedFile['attribute'];
            }
    
            if ($upload !== null) {
                $this->saveName .= '.' . $upload->getExtension();
                if (!in_array($upload->getExtension(), $this->pictureConfig['allowType'])) {
                    throw new ApiException(JsonResponseMsg::TYPE_NOT_ALLOWED, JsonResponseCode::TYPE_NOT_ALLOWED);
                }
                $originalPath = $this->uploadDir . DIRECTORY_SEPARATOR . $this->pictureConfig['originalDir'] . DIRECTORY_SEPARATOR . $this->savePath . DIRECTORY_SEPARATOR;
                $file = $this->apiWebPath . $originalPath . $this->saveName;
                $this->createDir($this->apiWebPath . $originalPath);
                if ($upload->saveAs($file) && $this->water($file) && $this->text($file) && $this->thumb($file)) {
                    JsonResponse::success()->pushData($name, ['savePath' => $originalPath, 'saveName' => $this->saveName, 'file' => $originalPath . $this->saveName]);
                } else {
                    if ($upload->getHasError()) {
                        $code = $upload->error;
                        switch ($code) {
                            case UPLOAD_ERR_INI_SIZE:
                                $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
                                break;
                            case UPLOAD_ERR_FORM_SIZE:
                                $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
                                break;
                            case UPLOAD_ERR_PARTIAL:
                                $message = "The uploaded file was only partially uploaded";
                                break;
                            case UPLOAD_ERR_NO_FILE:
                                $message = "No file was uploaded";
                                break;
                            case UPLOAD_ERR_NO_TMP_DIR:
                                $message = "Missing a temporary folder";
                                break;
                            case UPLOAD_ERR_CANT_WRITE:
                                $message = "Failed to write file to disk";
                                break;
                            case UPLOAD_ERR_EXTENSION:
                                $message = "File upload stopped by extension";
                                break;
    
                            default:
                                $message = "Unknown upload error";
                                break;
                        }
                        JsonResponse::setMessage($message);
                        JsonResponse::setCode(JsonResponseCode::PICTURE_UPLOAD_FAILED);
                    }
                    @unlink($file);
                }
            } else {
                $message = "No file was uploaded";
                JsonResponse::setMessage($message);
            }
        } catch (\Exception $ex) {
            if ($ex instanceof ApiException) {
                $code = $ex->getCode();
            } else {
                $code = JsonResponseCode::FAIL;
            }
            JsonResponse::fail($code, $ex->getMessage());
        }
        return JsonResponse::getInstance();
    }
    
    public function thumb($filename)
    {
    
        if ($this->pictureConfig['thumb'] === false) {
            return true;
        }
        $thumbDir = $this->pictureConfig['thumbDir'];
        $savePath = $this->uploadDir . DIRECTORY_SEPARATOR . $thumbDir . DIRECTORY_SEPARATOR . $this->savePath . DIRECTORY_SEPARATOR;
        $saveName = basename($filename);
        $this->createDir($this->apiWebPath . $savePath);
        $this->setImagesize($filename);
        if ($this->imagesize) {
            $width = round($this->imagesize[0] / $this->pictureConfig['minification']);
            $height = round($this->imagesize[1] / $this->pictureConfig['minification']);
            $this->checkImgSize($filename);
            //Image::thumbnail($filename, $width, $height)->save($this->apiWebPath . $savePath . $saveName);
    
            JsonResponse::pushData('thumb', ['savePath' => $savePath, 'saveName' => $saveName]);
            return true;
        }
        return false;
    }
    
    private function checkImgSize($filename)
    {
        $this->setImagesize($filename);
        if ($this->imagesize[0] > 3000 || $this->imagesize[1] > 3000) {
            throw new ApiException(JsonResponseMsg::PICTURE_SIZE_TOO_BIG, JsonResponseCode::PICTURE_UPLOAD_FAILED);
        }
    }
    
    private function water($filename)
    {
        try {
    
            if ($this->pictureConfig['water'] === false) {
                return true;
            }
            $this->checkImgSize($filename);
            $waterPosition = $this->pictureConfig['waterPosition'];
            $waterPicture = $this->pictureConfig['waterPicture'];
            if (!$waterPosition) {
                $imagesize = @getimagesize($waterPicture);
                $this->setImagesize($filename);
                $waterPosition = [mt_rand(0, abs($this->imagesize[0] - $imagesize[0])), mt_rand(0, abs($this->imagesize[1] - $imagesize[1]))];
            }
            Image::watermark($filename, $waterPicture, $waterPosition)->save();
            return true;
        } catch (\Exception $ex) {
            
        }
        return false;
    }
    
    public function text($filename)
    {
        try {
            if ($this->pictureConfig['text'] === false) {
                return true;
            }
            $this->checkImgSize($filename);
            $textPosition = $this->pictureConfig['textPosition'];
            if (!$textPosition) {
                $textPosition = [0, 0];
            }
            Image::text($filename, $this->pictureConfig['waterText'], $this->pictureConfig['waterFont'], $textPosition, ['color' => $this->pictureConfig['textColor'], 'size' => $this->pictureConfig['textSize']])->save();
            return true;
        } catch (\Exception $ex) {
            
        }
        return false;
    }
    
    private function createDir($dir)
    {
        if (!file_exists($dir) || !is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
    }
    
    private function setImagesize($filename)
    {
        $this->imagesize === null && $this->imagesize = @getimagesize($filename);
    }
    
  • 回答于 2017-08-24 15:06 举报

    这是一个支持单文件 多文件上传的

    控制器

     public function actionFiles(){
        $request = yii::$app->request;
        $model = new My_files();
        $flag = 1;
    
        if($request->isPost){
            $post = $request -> post();
            $imgs = UploadedFile::getInstances($model, 'img');
            if($imgs){
                foreach ($imgs as $img) {
                    $filename = 'uploads/img_' . time() . rand(1111,9999) . '.' . $img->extension;
                    $img->saveAs($filename);
    
                    $files = clone $model;
                    $files -> img = $filename;
                    // var_dump($files);die;
                    if(!$files -> save(false)){
                        $flag = 0;
                        return $this->rendercontent('上传失败');
                    }
                }
            }
            return $this->rendercontent('上传成功');
    
        }
    
        if($request->isGet){
            return $this->render('files.php',['model'=>$model]);
        }
    }
    

    视图

    $form = ActiveForm::begin(['method'=>'post','action' => ['aaa/files']]); ?>

    <?= $form->field($model, 'img[]')->fileInput(['multiple' => true]) ->label('上传图片')  ?>
    
    <?= $form->field($model, 'verifyCode')->textInput(['class'=>'dl_textinp'])->label('验证码') ?>
    <?= Captcha::widget(['name'=>'captchaimg','captchaAction'=>'aaa/captcha',
        'imageOptions'=>['id'=>'captchaimg', 'title'=>'换一个', 'alt'=>'换一个',
            'style'=>'cursor:pointer;margin-left:25px;'],'template'=>'{image}']);?>
    
    <?= Html::submitButton('点击提交') ?>
    

    <?php ActiveForm::end(); ?>

  • 回答于 2017-10-20 15:17 举报
您需要登录后才可以回答。登录 | 立即注册
alone_oo
职场新人

alone_oo

注册时间:2017-08-21
最后登录:2017-09-27
在线时长:5小时59分
  • 粉丝0
  • 金钱20
  • 威望0
  • 积分70

热门问题