在react.js和Yii2 API中上传文件

时间:2017-12-14 21:50:10

标签: javascript php ajax reactjs yii2-advanced-app

我在使用react.js(第15版),我想用yii2 api上传文件。
我的代码如下:
我的组件(反应):

import React, { Component } from 'react';
import Header from './Heaader';    
/* global $ */    

class New extends Component {    

    constructor(props){
        super(props);
    this.state = {
            cates: [],
            subcats: [],
            radioSelected: "f"
        };
    }    

    submitted = (e) => {

        e.preventDefault();

        var file_data = $('#filee')[0].files;
        var form_data = new FormData();
        form_data.append('file', file_data);    

        $.ajax({
        url: "http://blog.dev/ads",
        type: "POST",
        data:  form_data,
        contentType: false,
        cache: false,
        processData:false,
        success: function(data){
            console.log(data);
        },
        error: function(){}
       });
    };    

    render(){
        return (
            <div>
                <Header isNew="true" />
                <div style={{marginTop: 2 + 'em'}}>
                    <form onSubmit={this.submitted}>
                        <input type="file" id="filee" />
                        <button type="submit">Sub</button>

                    </form>
                </div>
            </div>

        );
}

服务器端:
在我的控制器中:

<?php

namespace frontend\controllers;

use Yii;
use yii\rest\ActiveController;    

class AdsController extends ActiveController
{
    public $modelClass = 'frontend\models\Ads';

    public function behaviors()
    {
        $behaviors = parent::behaviors();

        // remove authentication filter
        $auth = $behaviors['authenticator'];
        unset($behaviors['authenticator']);

        // add CORS filter
        $behaviors['corsFilter'] = [
            'class' => \yii\filters\Cors::className(),
        ];

        // re-add authentication filter
        $behaviors['authenticator'] = $auth;
        // avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
        $behaviors['authenticator']['except'] = ['options'];

        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['create']);
        return $actions;
    }

    public function actionCreate()
    {
        print_r($_FILES);
    }
}    

我的问题是$ _FILES数组是空的!
当我发送文件以外的数据时,$ _POST可以正常工作(在ajax请求中就是这种情况:processData:true和contentType:true)。
 但$ _FILES是空的。
请指导我并告诉我问题出在哪里?

1 个答案:

答案 0 :(得分:0)

  • 确保您的表单具有正确的编码,例如= 8 and用于文件上传。这很可能是您的.为空的原因
  • Yii 2使用is not null中的Set a local variable to tomorrow’s date: l_date := SYSDATE + 1; Move back one hour: l_date := SYSDATE - 1/24; Move ahead 10 seconds: l_date := SYSDATE + 10 / (60 * 60 * 24); 指定用于提取/保存上传的统一API。您应该使用它来访问上传。

所有最好的