Reactjs 如何在React JS中上载图像?

Reactjs 如何在React JS中上载图像?,reactjs,Reactjs,形象* 如果要上载图像并将其发布到API。然后安装react图像上传器。它通过发出POST请求将图像保存到本地端口和数据库中。从文件上载图像,并在react中显示在页面上, 您还可以在选择图像时获得处于状态的图像对象 要在网页上显示,必须使用URL.createObjectURL(fileObject)将图像对象转换为对象 import React,{Component}来自“React”; 类DisplayImage扩展组件{ 建造师(道具){ 超级(道具); 此.state={ 图像:空 }


形象*

如果要上载图像并将其发布到API。然后安装
react图像上传器
。它通过发出POST请求将图像保存到本地端口和数据库中。

从文件上载图像,并在react中显示在页面上, 您还可以在选择图像时获得处于状态的图像对象 要在网页上显示,必须使用URL.createObjectURL(fileObject)将图像对象转换为对象

import React,{Component}来自“React”;
类DisplayImage扩展组件{
建造师(道具){
超级(道具);
此.state={
图像:空
};
this.onImageChange=this.onImageChange.bind(this);
}
onImageChange=事件=>{
if(event.target.files&&event.target.files[0]){
设img=event.target.files[0];
这是我的国家({
图片:URL.createObjectURL(img)
});
}
};
render(){
返回(
选择图像
);
}
}
导出默认显示图像;
使用您可以非常轻松地执行此操作:

从“React”导入React;
从“@rpldy/Uploady”导入上传;
从“@rpldy/upload button”导入上载按钮;
从“@rpldy/upload preview”导入UploadPreview;
const filterBySize=(文件)=>{
//过滤掉大于5MB的图像
返回文件大小(
);
import React, { Component } from "react";

class DisplayImage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      image: null
    };

    this.onImageChange = this.onImageChange.bind(this);
  }

  onImageChange = event => {
    if (event.target.files && event.target.files[0]) {
      let img = event.target.files[0];
      this.setState({
        image: URL.createObjectURL(img)
      });
    }
  };

  render() {
    return (
      <div>
        <div>
          <div>
            <img src={this.state.image} />
            <h1>Select Image</h1>
            <input type="file" name="myImage" onChange={this.onImageChange} />
          </div>
        </div>
      </div>
    );
  }
}
export default DisplayImage;