ReactJS:如何使用Formik处理图像/文件上传?

人气:879 发布:2022-10-16 标签: reactjs react-redux reducers formik

问题描述

我正在使用ReactJS为我的网站设计个人资料页面。 现在我的问题是如何从本地计算机上传图像并将其保存到数据库并在个人资料页面中显示

import React, {Component} from 'react';
import { connect } from 'react-redux';
import { AccountAction } from '../../actions/user/AccountPg1Action';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';

class AccountInfo extends Component {
  constructor(props) {
    super(props) 
    this.state = {
      currentStep: 1,
      userAccountData: {
        userid: '',
        useravtar: '',
        attachement_id: '',
   }
  }
 }

handleFileUpload = (event) => {
  this.setState({useravtar: event.currentTarget.files[0]})
};

handleChange = event => {
    const {name, value} = event.target
    this.setState({
      [name]: value
    })    
  }

handleSubmit = event => {
    let that = this;
    const { AccountAction } = that.props;
    event.preventDefault();

    let accountInputs = {
      userid: 49,
      useravtar: that.state.image,
      attachement_id: 478,
}
    that.setState({
      userAccountData: accountInputs,
    })

    AccountAction(accountInputs)
  }
AccountInfoView = () => {
console.log(this.state.useravtar)
    return (
      <section id="account_sec" className="second_form">
      <div className="container">
      <React.Fragment>
        <Formik
          initialValues={‌{
            file: null,
            email: '',
            phone: ''
          }}
          validationSchema={accountInfoSchema}
          render={(values) => {
          return(
        <Form onSubmit={this.handleSubmit}>
        <Step1 
          currentStep={this.state.currentStep} 
          handleChange={this.handleChange}
          file= {this.state.useravtar}
          handleFileUpload={this.handleFileUpload}
          />
          </Form>
        );
      }}
      />
      </React.Fragment>
      )
  }

  render() {    

    return (
      <div>{this.authView()}</div>
    )
  }
}

function Step1(props) {
console.log(props.useravtar)
  if (props.currentStep !== 1) {
    return null
  } 

  return(
    <div className="upload">
        <label htmlFor="profile">
          <div className="imgbox">
            <img src="images/trans_116X116.png" alt="" />
            <img src={props.useravtar} className="absoImg" alt="" />
          </div>
        </label>
<input id="file" name="file" type="file" accept="image/*" onChange={props.handleFileUpload}/>
        <span className="guide_leb">Add your avatar</span>
      </div>
  )
}

当我在handleChange操作中对Event.Target.file[0]执行控制台操作时,它响应为unfined。

此外,在handleSubmit中执行console.log(this.state.useravtar)操作会显示类似c:/fakepath/imgname.jpg

的路径名 附注:我有多个表单,所以我以Step的方式使用它。我正在使用Redux Reducer来存储数据。

我引用了this链接,但我的要求不是这样的。

推荐答案

Formik默认不支持文件上传,但您可以尝试以下操作

<input id="file" name="file" type="file" onChange={(event) => {
  setFieldValue("file", event.currentTarget.files[0]);
}} />

此处"file"表示您用来存放文件的密钥

在提交时,您可以使用

获取文件的文件名、大小等
onSubmit={(values) => {
        console.log({ 
              fileName: values.file.name, 
              type: values.file.type,
              size: `${values.file.size} bytes`
            })

如果要将文件设置为组件状态,则可以使用

onChange={(event) => {
  this.setState({"file": event.currentTarget.files[0]})};
}}

根据您的代码,您必须按如下方式处理文件上传

在Account tInfo中添加处理文件上传的函数

handleFileUpload = (event) => {
this.setState({WAHTEVETKEYYOUNEED: event.currentTarget.files[0]})};
}

并将相同的函数传递给Step1组件,如下所示

    <Step1 
      currentStep={this.state.currentStep} 
      handleChange={this.handleChange}
      file= {this.state.image}
      handleFileUpload={this.handleFileUpload}
      />

在上传文件的Step1组件中,将输入更改为

<input id="file" name="file" type="file" accept="image/*" onChange={props.handleFileUpload}/>

如果您需要预览上传的图片,则可以创建一个BLOB并将其作为图片的源代码传递,如下所示

<img src={URL.createObjectURL(FILE_OBJECT)} /> 

编辑-1

由于安全问题,URL.createObjectURL方法被弃用,我们需要对Media元素使用srcObject,以使用您可以使用ref来分配srcObject,例如

假设您正在使用类组件,

构造函数

在构造函数中可以使用

constructor(props) {
  super(props)
  this.imageElRef = React.createRef(null)
}

处理更改功能

handleFileUpload = (event) => {
  let reader = new FileReader();
let file = event.target.files[0];
reader.onloadend = () => {
  this.setState({
    file: reader.result
  });
};
reader.readAsDataURL(file);
}

元素

<img src={this.state.file} /> 

119