我对reactjs很陌生,我的目标是上传一个表单中的文件(表单用于联系no.of数据,即姓名、电子邮件、电话号码等),我无法想出如何上传该文件。我的意思是我需要以哪种格式上传文件。在后端,我们使用类似于这个链接"File upload with ASP.Net Core 2.0 Web API and React.js“的iform文件,并用这样的方式显示:
以下是代码:
<Form.Field>
<label>File upload </label>
<Button as="label" htmlFor="file" type="button" animated="fade">
<Button.Content visible>
<Icon name="file" />
</Button.Content>
<Button.Content hidden>Choose a File</Button.Content>
</Button>
<input
type="file"
id="file"
hidden
onChange={this.props.FileCheck}
/>
<Form.Input
fluid
label="File Chosen: "
placeholder="Use the above bar to browse your file system"
readOnly
value={this.state.fileName}
/>
</Form.Field>
下面是我刚刚为上传文件创建的示例"https://codesandbox.io/s/red-feather-77v26“。
我要这样做:
当我单击submit时,它将显示不支持的媒体文件。有人能帮我吗?
发布于 2020-04-18 11:01:00
我已经重写了FileUpload组件和显示组件如下。请检查一下。应该管用的。
FileUpload组件
import React from "react";
import {Grid, Label, Button, Icon, Form} from "semantic-ui-react";
export default class FIleUpload extends React.Component {
constructor(props) {
super(props);
};
fileUpload = (e) => {
this.props.setFile(e.target.files[0], e.target.files[0].name);
};
render() {
return (
<Grid>
<Grid.Row>
<Label className="FileLab">File Upload</Label>
<Button as="label" htmlFor="file" type="button" animated="fade">
<Button.Content visible>Choose a File</Button.Content>
<Button.Content hidden>
<Icon name="file"/>
</Button.Content>
</Button>
<input type="file" id="file" hidden onChange={this.fileUpload}/>
<Form.Input
className="myfileName"
label="file name"
placeholder="Use the above bar to browse your file system"
readOnly
value={this.props.fileName}
/>
</Grid.Row>
</Grid>
);
}
}
显示组件
import React from "react";
import {render} from "react-dom";
import {Form, Button} from "semantic-ui-react";
import axios from "axios";
import FIleUpload from "./FIleUpload";
export default class Display extends React.Component {
constructor(props) {
super(props);
this.state = {
file: null,
fileName: ""
};
}
setFile = (file, name) => {
this.setState({
file: file,
fileName: name
});
};
handleSubmit = event => {
event.preventDefault();
const formData = new FormData();
formData.append("file", this.state.file);
const data = {
file: this.state.file,
fileName: this.state.fileName
};
axios
.post(`/api/FormDetails`, data, {
headers: {"Content-Type": "multipart/form-data"}
})
.then(res => {
console.log(res);
});
};
render() {
return (
<div>
<Form>
<FIleUpload setFile={this.setFile}/>
<br/>
<Form.Group align="center">
<Form.Field fluid control={Button} onClick={this.handleSubmit}>
{" "}
SUBMIT{" "}
</Form.Field>
</Form.Group>
</Form>
</div>
);
}
}
https://stackoverflow.com/questions/61287476
复制相似问题