【发布时间】:2019-09-30 05:14:31
【问题描述】:
首先,我不是英语本地人。所以,我的句子可能在语法上是错误的,或者难以表达意思。
我有一个使用 Laravel 和 Axios 的 React 项目。我想在我的服务器上上传图像数据。所以,我尝试在文件上传时将文件数据设置为跟随this document,但它不起作用。
我想知道为什么它不起作用。
这是我的一些代码。
import Axios from 'axios';
import React, { Component } from 'react';
class Register extends Component {
constructor() {
super();
this.state = {
name: '',
email: '',
password: '',
password_confirmation: '',
profile_picture: null,
errors: [],
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.hasErrorFor = this.hasErrorFor.bind(this);
this.renderErrorFor = this.renderErrorFor.bind(this);
}
handleChange(event) {
if(event.target.name.match('profile_picture')) {
// when input profile picture
this.setState({
[event.target.name]: event.target.files[0],
});
console.log(event.target.files[0]);
} else {
// when input text values
this.setState({
[event.target.name]: event.target.value,
});
}
console.log(this.state);
}
handleSubmit(event) {
// submit event
}
hasErrorFor(field) {
// detect error
}
renderErrorFor(field) {
// render error message
}
render() {
return (
<div className="container">
<div className="row justify-content-center">
<div className="col-md-8">
<div className="card">
<div className="card-header">Register</div>
<div className="card-body">
<form
action="/api/register"
method="post"
encType='application/x-www-form-urlencoded'
onSubmit={this.handleSubmit}
>
<div className="form-group">
// input name
</div>
<div className="form-group">
// input email
</div>
<div className="form-group">
// input password
</div>
<div className="form-group">
// input password confirmation
</div>
<div className="form-group">
<label htmlFor="profile_picture">Profile Picture</label>
<input
id="profile_picture"
type="file"
name="profile_picture"
className='form-control-file'
onChange={this.handleChange}
/>
{this.renderErrorFor('profile_picture')}
</div>
<button className="btn btn-primary">SUBMIT</button>
</form>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Register;
And here is result of this code.
我上传文件的时候除了上传的文件设置为状态,但是文件没有设置为状态。
【问题讨论】:
标签: javascript reactjs file multipartform-data form-data