WinterCMS在前端实现上传图片

上一次在WinterCMS中创建了一个可以在前端通过ajax提交数据的component,今天在此基础上实现带有图片上传的表单数据提交,不一样的是这次用传统的form action来完成。

在此之前需要在后台把Model中添加一个file upload的字段。

Tips: 如果需要使用ajax请求则需要在form中添加data-request-filesdata-request-flash这两个参数。

前端文件

default.htm

注意替换代码中"your-page-slug","awardimage","award_title"等相关字段

<form method="post" action="{{ url('your-page-slug') }}" accept-charset="UTF8" enctype="multipart/form-data">
    <input type="hidden" name="_handler" value="onSave">
    {{ form_token() }}
    {{ form_sessionKey() }}
    <label>Award Title</label>
    <input type="text" name="award_title">
    {{ errors.first('award_title') }}
    <label>Award image</label>
    <input type="file" name="awardimage">
    <button type="submit">Save Award</button> 
    {% flash success %}
    <p>{{ message }}</p>
    {% endflash %}   
    {% for error in errors.all() %}
    <p>{{ error }}</p>
    {% endfor %}       
</form>

核心文件

awardForm.php

<?php namespace Julian\Library\Components;
use Cms\Classes\ComponentBase;
use Input;
use Validator;
use ValidationException;
use Redirect;
use Julian\Library\Models\Award;
use Flash;

class AwardForm extends ComponentBase{
    public function componentDetails(){
        return [
            'name' => 'Award Form',
            'description' => 'Enter Awards'
        ];
    }

    public function onSave(){
        
        $validator = Validator::make(
            //Data
            [
                'award_title' => Input::get('award_title')
            ],
            //Rules
            [
                'award_title' => 'required|min:5|unique:julian_library_awards,award_title'
            ]
        );

        if($validator->fails()){
            return Redirect::back()->withErrors($validator);
            //Flash::error($validator); //AJAX request custom error message
            //throw new ValidationException($validator);    //AJAX request system error message
        }else{
            $award = new Award();
            $award->award_title = Input::get('award_title');
            $award->slug = str_slug(Input::get('award_title'));
            $award->awardimage = Input::file('awardimage');
            $award->save();
            Flash::success('Award added!'); 
        }


    }
}

补充阅读:表单的处理与消息捕捉

Post Comment