带环回的存储组件-axios.post上传文件待处理[反应]

时间:2019-03-10 10:59:02

标签: reactjs axios loopback

我正在尝试将图像上传到./images,但是我的axios请求正在等待处理。

image

我不明白为什么。就像它在等待响应。 我已经从环回中读取了documentation。请告诉我是否需要有关该问题的更多详细信息。

这是我的代码:

import React, { Component } from "react";
import axios from "axios";

export default class ImagesUploaded extends Component {
  constructor(props) {
    super(props);
    this.state = {
      file: "",
      imagePreviewUrl: "",
      nameImage: "",
      disabled: false
    };
  }

  changeName() {
    var nameAvecEspace = this.state.file.name;
    var nameAvecTiret = nameAvecEspace.replace(/ /g, "_");
    this.setState({ nameImage: nameAvecTiret });
  }

  _handleSubmit(e) {
    e.preventDefault();
    this.changeName();
    const data = this.state.file;
    console.log("data : ", data);
    axios
      .post(
        `http://localhost:3002/api/images/images/upload/?access_token=${localStorage.getItem("userId")}`,
        data
      )
      .catch(err => {
        console.log(err);
      });

    console.log("handle uploading-", this.state.file);
  }

  _handleImageChange(e) {
    e.preventDefault();

    let reader = new FileReader();
    let file = e.target.files[0];

    reader.onloadend = () => {
      this.setState({
        file: file,
        imagePreviewUrl: reader.result
      });
    };

    reader.readAsDataURL(file);
  }

  render() {
    let { imagePreviewUrl } = this.state;
    let $imagePreview = null;
    if (imagePreviewUrl) {
      $imagePreview = (
        <img
          src={imagePreviewUrl}
          alt=""
          style={{ maxWidth: "250px", maxHeight: "250px" }}
        />
      );
      this.state.disabled = false;
    } else {
      $imagePreview = (
        <div className="previewText">
          Veuillez selectionner une image pour une prévisualisation
        </div>
      );
      this.state.disabled = true;
    }

    return (
      <div className="previewComponent">
        <form onSubmit={e => this._handleSubmit(e)}>
          <input
            className="fileInput"
            type="file"
            encType="multipart/form-data"
            onChange={e => this._handleImageChange(e)}
          />
          <button
            className="submitButton"
            type="submit"
            disabled={this.state.disabled}
            onClick={e => this._handleSubmit(e)}
          >
            Charger l'image
          </button>
        </form>
        <div className="imgPreview">{$imagePreview}</div>
      </div>
    );
  }
}

PS:我可以添加容器,所以我认为模型不是问题。

0 个答案:

没有答案