duanba8173 2019-03-14 08:07
浏览 272

Yii2 Ajax使用FormData提交 - 控制器未接收POSTED文件数据

I have an activeform using Ajax POST and the form fields are being sent, however it seems the file data is not. Here is the logically relevant code snippets from my files, underneath them is commentary on the test using a JS alert and the result

ActiveForm:

<?= $form->field($model, 'userphoto')->fileInput() ?>

Ajax Submit:

$script = <<< JS

$('form#{$model->formName()}').on('beforeSubmit', function(event)
{

    event.preventDefault();


    var form = $(this);

        formdata = new FormData(form[0]);

            $.ajax({
            url    : form.attr('action'),
            data        : formdata,
            cache       : false,
            contentType : false,
            processData : false,
            type        : 'POST',

            success: function (response) 
            {   
                alert(JSON.stringify(response.status);
                $.pjax.reload({container:'#usergrid'});
                $(form).trigger('reset'); 


            },
            });
            return false;
         });


JS;
$this->registerJs($script);

?>

Model:

use yii\web\UploadedFile;

class Usermanager extends \yii\db\ActiveRecord
{
    public static function tableName()
    {
        return 'user';
    }

    public $userphoto;

    public function rules()
    {
        return [

        [['userphoto'], 'file', 'extensions' => 'jpg, png, gif', 
'skipOnEmpty' => true],

Controller:

namespace app\controllers;

use Yii;
use app\models\Usermanager;
use yii\web\Controller;
use yii\web\Response;
use yii\web\UploadedFile;

class UsermanagerController extends Controller
{

 public function actionCreate()
 {
  $model = new Usermanager();


  if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && Yii::$app->request->enableCsrfValidation)
  {
    Yii::$app->response->format = 'json';

    $userphoto = UploadedFile::getInstance($model, 'userphoto');
    /* return ['status' => $userphoto];  */
    $model->photo = "web/". $model->username. "." .$userphoto->extension;


        if($model->password !==''){
            $model->password = Yii::$app->security->generatePasswordHash($model->password);
        }

    if($model->validate())
    {   

        $model->save();

    }
    else
    {
    return ActiveForm::validate($model);  
        }
    }

   return $this->renderAjax('create', [
      'model' => $model
    ]);

  }

Here is the JS alert test result:

The test - (controller receives POST)

$userphoto = UploadedFile::getInstance($model, 'userphoto');
return ['status' => $userphoto];

The test result -> alert(JSON.stringify(response.status)):

{"name":"kde.jpg","tempName":"/tmp/phpjp3i4d",
"type":"image/jpeg","size":51253,"error":0}

As you can see the alert details the file attributes as if the file was received. However if an attempt is made to source the file extension thus:

$model->photo = "web/". $model->username. "." .$userphoto->extension;

The extension cannot be found. Further I have also tried to save with $userphoto->saveAs, however the console.log reports could not save null().

So does anyone have a successfully integrated AJAX Submit with file upload using YII2 that is maybe not using a Kartik widget ?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 如何在scanpy上做差异基因和通路富集?
    • ¥20 关于#硬件工程#的问题,请各位专家解答!
    • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
    • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
    • ¥30 截图中的mathematics程序转换成matlab
    • ¥15 动力学代码报错,维度不匹配
    • ¥15 Power query添加列问题
    • ¥50 Kubernetes&Fission&Eleasticsearch
    • ¥15 報錯:Person is not mapped,如何解決?
    • ¥15 c++头文件不能识别CDialog