在reactjs中显示文件上载消息成功或失败

时间:2017-04-26 05:06:13

标签: javascript ajax twitter-bootstrap reactjs

我在服务器上使用Ajax调用上传文件。所以我想表现出成功与否根据文件上传的失败消息

  $.ajax({
  url: "https:my_url",
  data: {my data: my_data},
  method : "POST",
  success: function(result) {
    alert(result);
  },
  error: function(error){
    alert("Error in File Upload");
   }
  });

在反应组件中使用

<input id="file-input" type="file" className="fileInput" onChange=
{this.myfile} multiple />

请帮我把打印信息作为引导程序或任何好的方式即  需要如下

<div class="alert alert-success">
<strong>Success!</strong> You should <a href="#" class="alert-
link">File uploaded </a>.
</div>

1 个答案:

答案 0 :(得分:0)

像这样有一个CSS类invisible

.invisible{
display:none;
}

然后有一个状态变量uploaded,初始值为uploading

this.state = {uploaded:'uploading'}

然后创建两条警报消息

<div className=`alert alert-success ${this.state.uploading === 'success'?'':'invisible'}`>
<strong>Success!</strong> You should <a href="#" class="alert-
link">File uploaded </a>.

<div className=`alert alert-danger ${this.state.uploading === 'failure'?'':'invisible'}`>
<strong>Failure!</strong> Failed <a href="#" class="alert-
link">File uploaded </a>.
</div>

这里发生的是成功消息仅在this.state.uploading等于'成功'时显示,而失败消息在等于'失败'时显示。

然后在ajax电话

 $.ajax({
  url: "https:my_url",
  data: {my data: my_data},
  method : "POST",
  success: (result) => {
     this.setState({uploading:'success'})
  },
  error: (error) => {
     this.setState({uploading:'failure'})
   }
  });

ajax调用将this.state.uploading设置为成功或失败,具体取决于ajax调用的结果,并显示相应的消息。

对于ES5风格

 var _this = this
 $.ajax({
  url: "https:my_url",
  data: {my data: my_data},
  method : "POST",
  success: function (result) {
     _this.setState({uploading:'success'})
  },
  error: function (error) {
     _this.setState({uploading:'failure'})
   }
  });