Javascript 在ReactJS中上载表单中的2个文件

Javascript 在ReactJS中上载表单中的2个文件,javascript,reactjs,axios,semantic-ui-react,Javascript,Reactjs,Axios,Semantic Ui React,我有3个错误: 一, 三, 这就是我的网页的样子 这是我的代码: import React, { Component } from 'react'; import axios from 'axios'; import { Form, TextArea, Button, Grid, Segment, Header } from 'semantic-ui-react' class UploadScreen extends Component { constructor(){

我有3个错误:

一,

三,

这就是我的网页的样子

这是我的代码:

import React, { Component } from 'react';
import axios from 'axios';
import { Form,  TextArea, Button, Grid, Segment, Header } from 'semantic-ui-react'

class UploadScreen extends Component {
    constructor(){
        super();
        this.state={
          title:'',
          tags:'',
          description: '',
          viewing_time: '',
          file: null,
          preview: null,
          url: '',
          errors: {}
        }
       }

    fileChangedHandler = (event) => {
        this.setState({file: event.target.files[0]})
    }

    previewChangedHandler = (event) => {
        this.setState({preview: event.target.files[0]})
    }

    onChange = (e) => {
        this.setState({ [e.target.name]: e.target.value });
       }

    onSubmit = (e) => {
        const formData = new FormData()
        formData.append('file', this.state.file, this.state.file.name)
        const previewData = new FormData()
        previewData.append('preview', this.state.preview, this.state.preview.name)

        var token = localStorage.getItem('jwt');
        var apiBaseUrl = "http://127.0.0.1:8000/api/materials";
        var payload={
            "title":this.state.title,
            "tags":this.state.tags,
            "description":this.state.description,
            "viewing_time":this.state.viewing_time,
            "url":this.state.url
        }
        var config = {
          headers: {
            'Authorization': "bearer " + token,
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          withCredentials: false
        }

        axios.post(apiBaseUrl, payload, formData, previewData, config)
        .then(function (response) {
          console.log(response);
          if(response.status == 200){
              console.log("success");
          }
          else if(response.status == 204){
              console.log("nope");
          }
          else{
              console.log("nope nope");
          }
      })
      }

    render() {
        const { title, tags, description, viewing_time, file, preview, url, errors } = this.state;
        return (
            <Grid textAlign='center' style={{ height: '100%' }} verticalAlign='middle'>
            <Grid.Column style={{ maxWidth: 1000 }}>
            <br />
            <br />
            <br />
            <Header as='h1'>Create a New Material</Header>
            <Form onSubmit={this.onSubmit}>
                <Segment stacked>
            <Header as='h2' textAlign='left'>Details</Header>
            <Form.Input
            type='text'
            name='title'
            value={title}
            onChange={this.onChange}            
            placeholder='Title' 
            fluid
            icon='pencil'
            iconPosition='left' 
            />

            <Form.Group widths='equal'>
              <Form.Input
                type='text'
                name='viewing_time'
                value={viewing_time}
                onChange={this.onChange}    
                placeholder='Viewing Time'
                fluid
                icon='clock'
                iconPosition='left'
              />
              <Form.Input
                type='text'
                name='tags'
                value={tags}
                onChange={this.onChange}                
                placeholder='Tags (multiple tags must be separated by semi-colon)'
                fluid
                icon='tags'
                iconPosition='left'
              />
            </Form.Group>
            <Form>
            <TextArea
                name='description'
                value={description}
                onChange={this.onChange}     
                autoHeight 
                placeholder='Description' 
                fluid
            />
            </Form>
            <Header as='h2' textAlign='left'>Material Upload</Header>
            <Form>
                <input type="file" class="form-control-file" id="file" name='file' onChange={this.fileChangedHandler}  aria-describedby="fileHelp" />
            <Header as='h3'>or</Header>
            <Form.Input
                name='url'
                value={url}
                onChange={this.onChange}  
                placeholder='File URL'
                fluid
                icon='world'
                iconPosition='left'
              />
            </Form>
            <Header as='h2' textAlign='left'>Material Preview</Header>
            <Form>
                <input type="file" class="form-control-file" id="preview" name='preview' onChange={this.previewChangedHandler} aria-describedby="fileHelp" />
            </Form>
            <br />
            <Button fluid size='large' type="submit">
                Create
            </Button>
            </Segment>
          </Form>
          </Grid.Column>
          </Grid>
        );
    }
}
export default UploadScreen;
import React,{Component}来自'React';
从“axios”导入axios;
从“语义ui react”导入{Form、TextArea、Button、Grid、Segment、Header}
类UploadScreen扩展组件{
构造函数(){
超级();
这个州={
标题:“”,
标签:“”,
说明:“”,
查看时间:“”,
文件:null,
预览:空,
url:“”,
错误:{}
}
}
fileChangedHandler=(事件)=>{
this.setState({file:event.target.files[0]})
}
previewChangedHandler=(事件)=>{
this.setState({preview:event.target.files[0]})
}
onChange=(e)=>{
this.setState({[e.target.name]:e.target.value});
}
onSubmit=(e)=>{
const formData=new formData()
formData.append('file',this.state.file,this.state.file.name)
const previewData=新表单数据()
previewData.append('preview',this.state.preview,this.state.preview.name)
var-token=localStorage.getItem('jwt');
var apiBaseUrl=”http://127.0.0.1:8000/api/materials";
var有效载荷={
“标题”:this.state.title,
“标签”:this.state.tags,
“description”:this.state.description,
“查看时间”:this.state.viewing\u time,
“url”:this.state.url
}
变量配置={
标题:{
“授权”:“持票人”+代币,
“接受”:“应用程序/json”,
“内容类型”:“应用程序/json”,
},
withCredentials:false
}
post(apiBaseUrl、有效负载、表单数据、预览数据、配置)
.然后(功能(响应){
控制台日志(响应);
如果(response.status==200){
控制台日志(“成功”);
}
else if(response.status==204){
控制台日志(“nope”);
}
否则{
控制台日志(“nope nope”);
}
})
}
render(){
const{title,tags,description,viewing_time,file,preview,url,errors}=this.state;
返回(



创建新材质 细节 材料上传 或 材质预览
创造 ); } } 导出默认上载屏幕;

我只是使用了教程中上传图片的方法,但它给了我错误。我想上传两个不同的文件,一个pdf和一个图像到axios请求,作为表单的一部分。我可能做错了什么

您只需要一个FormData实例,然后需要将所有字段(包括要发布的文件和其他输入)附加到该实例

然后在Axios中只发送Axios({…,data:data})

Esit-输入Ipad上的即时通讯,如果很难阅读,很抱歉,但是很难输入
POST http://127.0.0.1:8000/api/materials 422 (Unprocessable Entity)
createError.js:16 Uncaught (in promise) Error: Request failed with status code 422
at createError (createError.js:16)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)
import React, { Component } from 'react';
import axios from 'axios';
import { Form,  TextArea, Button, Grid, Segment, Header } from 'semantic-ui-react'

class UploadScreen extends Component {
    constructor(){
        super();
        this.state={
          title:'',
          tags:'',
          description: '',
          viewing_time: '',
          file: null,
          preview: null,
          url: '',
          errors: {}
        }
       }

    fileChangedHandler = (event) => {
        this.setState({file: event.target.files[0]})
    }

    previewChangedHandler = (event) => {
        this.setState({preview: event.target.files[0]})
    }

    onChange = (e) => {
        this.setState({ [e.target.name]: e.target.value });
       }

    onSubmit = (e) => {
        const formData = new FormData()
        formData.append('file', this.state.file, this.state.file.name)
        const previewData = new FormData()
        previewData.append('preview', this.state.preview, this.state.preview.name)

        var token = localStorage.getItem('jwt');
        var apiBaseUrl = "http://127.0.0.1:8000/api/materials";
        var payload={
            "title":this.state.title,
            "tags":this.state.tags,
            "description":this.state.description,
            "viewing_time":this.state.viewing_time,
            "url":this.state.url
        }
        var config = {
          headers: {
            'Authorization': "bearer " + token,
            'Accept': 'application/json',
            'Content-Type': 'application/json',
          },
          withCredentials: false
        }

        axios.post(apiBaseUrl, payload, formData, previewData, config)
        .then(function (response) {
          console.log(response);
          if(response.status == 200){
              console.log("success");
          }
          else if(response.status == 204){
              console.log("nope");
          }
          else{
              console.log("nope nope");
          }
      })
      }

    render() {
        const { title, tags, description, viewing_time, file, preview, url, errors } = this.state;
        return (
            <Grid textAlign='center' style={{ height: '100%' }} verticalAlign='middle'>
            <Grid.Column style={{ maxWidth: 1000 }}>
            <br />
            <br />
            <br />
            <Header as='h1'>Create a New Material</Header>
            <Form onSubmit={this.onSubmit}>
                <Segment stacked>
            <Header as='h2' textAlign='left'>Details</Header>
            <Form.Input
            type='text'
            name='title'
            value={title}
            onChange={this.onChange}            
            placeholder='Title' 
            fluid
            icon='pencil'
            iconPosition='left' 
            />

            <Form.Group widths='equal'>
              <Form.Input
                type='text'
                name='viewing_time'
                value={viewing_time}
                onChange={this.onChange}    
                placeholder='Viewing Time'
                fluid
                icon='clock'
                iconPosition='left'
              />
              <Form.Input
                type='text'
                name='tags'
                value={tags}
                onChange={this.onChange}                
                placeholder='Tags (multiple tags must be separated by semi-colon)'
                fluid
                icon='tags'
                iconPosition='left'
              />
            </Form.Group>
            <Form>
            <TextArea
                name='description'
                value={description}
                onChange={this.onChange}     
                autoHeight 
                placeholder='Description' 
                fluid
            />
            </Form>
            <Header as='h2' textAlign='left'>Material Upload</Header>
            <Form>
                <input type="file" class="form-control-file" id="file" name='file' onChange={this.fileChangedHandler}  aria-describedby="fileHelp" />
            <Header as='h3'>or</Header>
            <Form.Input
                name='url'
                value={url}
                onChange={this.onChange}  
                placeholder='File URL'
                fluid
                icon='world'
                iconPosition='left'
              />
            </Form>
            <Header as='h2' textAlign='left'>Material Preview</Header>
            <Form>
                <input type="file" class="form-control-file" id="preview" name='preview' onChange={this.previewChangedHandler} aria-describedby="fileHelp" />
            </Form>
            <br />
            <Button fluid size='large' type="submit">
                Create
            </Button>
            </Segment>
          </Form>
          </Grid.Column>
          </Grid>
        );
    }
}
export default UploadScreen;