如何在ReactJs中上传图像作为输入字段?

时间:2019-03-06 10:47:18

标签: javascript reactjs state

有多个输入字段,例如文本/整数/日期...和图像 一切正常,选择一个文件平滑流畅,但将其上传到数据库后出现一个错误:

 TypeError: _this.state.selectedFile is null


// ************Pets
>
onSubmit = evt => {
    evt.preventDefault();
    const {
      name ``
      `

以下是代码(错误很可能来自 state ):

const endpoint = "http://localhost:8000/upload";

class Pets extends Component {
state = {
// error_message: "",
pets_list: [],
selectedFile: null,
loaded: 0
 };

//For image upload with Loading bar

 handleSelectedFile = event => {
 this.setState({
  selectedFile: event.target.files[0],
  loaded: 0
   });
  };
  handleUpload = () => {
   const data = new FormData();
    data.append("file", this.state.selectedFile,       
   this.state.selectedFile.name);
   axios
  .post(endpoint, data, {
    onUploadProgress: ProgressEvent => {
      this.setState({
        loaded: (ProgressEvent.loaded / ProgressEvent.total) * 100
      });
    }
  })
  .then(res => {
    console.log(res.statusText);
  });
 };
   ...

然后在输入中,我们提供:

   <div>
          <input
            style={{ margin: "10px" }}
            type="file"
            name=""
            id=""
            onChange={this.handleSelectedFiles}
          />
          <button onClick={this.handleUpload}>Upload</button>
          <div>{Math.round(this.state.loaded, 2)} %</div>
        </div>
      </div>

错误指向此处

onSubmit = evt => {
evt.preventDefault();
const {
  name,
  image,
  gender,
  date_of_birth,
  species,
  info,
  availabilty
} = this.state;

让我知道是否需要更多代码。

0 个答案:

没有答案