【发布时间】:2019-10-02 14:56:03
【问题描述】:
我正在使用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] 操作控制台时,它会以未定义的方式响应。
另外,在handleSubmit 操作中执行console.log(this.state.useravtar) 会显示类似c:/fakepath/imgname.jpg 的路径名
P.S:我有多种形式,所以我在 Step 明智地使用它。我正在使用 Redux Reducer 来存储数据。
我已经提到了this 链接,但我的要求不是这样。
【问题讨论】:
-
您是否尝试过使用表单数据对象 - developer.mozilla.org/en-US/docs/Web/API/FormData/…
-
@SumanthMadishetty :我使用了 Formik 库,所以我使用了该库中的
Field组件。 jaredpalmer.com/formik -
@Taalavya formik 没有文件上传组件,你必须使用html输入并使用formik的`setFieldValue`方法来设置数据
标签: reactjs react-redux reducers formik