我正在使用 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] 操作进行控制台时,它会以未定义的方式响应。
此外,在 console.log(this.state.useravtar)
中执行 handleSubmit
操作它会显示类似 c:/fakepath/imgname.jpg
的路径名
PS:我有多种形式,所以我在 Step
明智地使用它。我正在使用 Redux Reducer 来存储数据。
我已经提到 了这个 链接,但我的要求不是这样的。
原文由 TMA 发布,翻译遵循 CC BY-SA 4.0 许可协议
Formik 默认不支持文件上传,但是你可以试试下面的
这里
"file"
代表你用来保存文件的密钥在提交时,您可以通过使用获取文件的文件名、大小等
如果要将文件设置为组件状态,则可以使用
根据您的代码,您必须按如下方式处理文件上传
在 AccountInfo 添加一个函数来处理文件上传
并将相同的函数传递给 Step1 组件,如下所示
在上传文件的 Step1 组件中,将输入更改为
如果您需要预览上传的图像,则可以创建一个 blob 并传递与图像源相同的内容,如下所示
编辑-1
由于
URL.createObjectURL
方法由于安全问题已被弃用,我们需要使用srcObject
用于媒体元素,使用您可以使用ref
来分配示例假设您正在使用类组件,
构造函数
在构造函数中你可以使用
手柄更换功能
元素