文件上传错误 - PHP和React

时间:2016-04-14 21:54:34

标签: php reactjs

我正在尝试使用React触发PHP脚本进行文件上传并将其保存在另一个文件夹位置。我可以通过普通的HTML / PHP来做到这一点但是当我尝试使用react做的时候,我得到以下错误。以下是它的完整代码。如果有人能够看到它并指导我完成这一点,我们将非常感激。

<body>
<div id="container" class="center" >
<!-- This element's contents will be replaced with your component. -->
</div>
<script type="text/jsx">
var Form = React.createClass({
    getInitialState() {
        return {
            fileInput: "",
        };
    },

    _onFileChange: function (event) {
        this.setState({fileInput: event.target.value});
    },

    handleSubmit(event) {
        event.preventDefault();
        var data = this.state;
        $.ajax({
            type: "POST",
            crossDomain: true,
            url: "http://localhost:8082/PFT/uploads.php",
            data: data,
            success: function(data){
                alert(data);
                $('#para').html(data);
            },
            error:function(data)
            {
                alert("Data sending failed");
            }
        });
    },

    render() {
        return (
                <form onSubmit={this.handleSubmit}>

                    <input id="fileInput" name="fileInput" type="file" value={this.state.fileInput} onChange={this._onFileChange} />
                    <button type="submit">Submit</button><br/><br/><br/>
                    <paragraph id="para" color="red">   Result will be printed here </paragraph>
                </form>

        )
    }
});

React.render(<Form />, document.getElementById('container'));
</script>
</body>

PHP文件:

  <?php header('Access-Control-Allow-Origin: *');

  $target_path = "uploads/";

 $target_path = $target_path . basename ( $_FILES['fileInput']['name']);

 if(move_uploaded_file ($_FILES['fileInput']['tmp_name'], $target_path)) {
  echo "The file ".  basename ( $_FILES['fileInput']['name']).
  " has been uploaded";
 } else{
  echo "There was an error uploading the file, please try again!";
 }
?>

错误:

 ! ) Notice: Undefined index: fileInput in C:\wamp\www\PFT\uploads.php on line 5
   Call Stack
  # Time    Memory  Function    Location
  1 0.0010  242344  {main}( )   ..\uploads.php:0

1 个答案:

答案 0 :(得分:1)

您没有上传文件,这就是您的$_FILES为空的原因。

请参阅here中有关如何使用react:

上传文件的示例
uploadfile: function(){ 
  var file = this.refs.file.getDOMNode().files[0];
  var reader = new FileReader();
  reader.onload = function(output){
    fileUpload.set({
      file: output.target.result 
    });
    fileUpload.save();
  }.bind(this));

  reader.readAsDataURL(file);
},
render: function(){
  <form onSubmit={uploadFile}>
    <input type="file" name="file" ref="file" defaultValue={this.state.file} /><br /> 
    <input type="submit" />
  </form>
}

或者,您可以使用React生成一个正常的表单:

return (<form action="uploads.php" method="post" enctype="multipart/form-data">
    <input type="file" name="fileInput">
    <input type="submit" value="Upload">
</form>);