简体   繁体   English

Django Rest Framework+React JS,无法实现表单解析器(错误:提交的数据不是文件。检查表单上的编码类型。)

[英]Django Rest Framework+React JS ,unable to implement form parser (error: The submitted data was not a file. Check the encoding type on the form.)

When I submit a form from react frontend with images server responds "The submitted data was not a file. Check the encoding type on the form."当我从带有图像的反应前端提交表单时,服务器响应"The submitted data was not a file. Check the encoding type on the form." . . When I use Django RF browsable API I can successfully add images.当我使用 Django RF 可浏览 API 时,我可以成功添加图像。 Will this be a problem from frontend then?那么这会是前端的问题吗?

VIEWS.PY意见.PY

class PostListCreateview(generics.ListCreateAPIView):
    queryset = Post.objects.all().order_by('id')
    serializer_class = PostSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    parser_class = (FileUploadParser,)
    def perform_create(self, serializer):

        serializer.save(author=self.request.user)

The Post model accepts title,body and pic as parameters from the form POST methods. Post model 接受来自表单 POST 方法的title,body and pic作为参数。

REACT FRONTEND反应前端

const [image,setImage] = useState(null)

    const handlesubmit =()=>{
        let endpoint = `/api/post/`;
        apiService(endpoint,'POST',{title:title,body:body,pic:image}).then(data=>
         console.log(data))};

    return (<input type="file"  onChange={(e)=>setImage(e.target.files[0])}/>
              <Button onClick={handlesubmit} >Upload</Button>)

Found the answer, https://medium.com/@emeruchecole9/uploading-images-to-rest-api-backend-in-react-js-b931376b5833找到了答案, https://medium.com/@emeruchecole9/uploading-images-to-rest-api-backend-in-react-js-b931376b5833


import React,{useState} from 'react'

function Addpost() {
    const [title,setTitle] = useState('dfv')
    const [body,setBody] = useState('vdfvdfd')
    const [picture, setPicture] = useState(null);


    const handlesubmit = (e)=>{
      e.preventDefault();
      let form_data = new FormData();
      form_data.append('pic', picture, picture.name);
      form_data.append('title', title);
      form_data.append('body', body);
      let url = '/api/post/';
      axios.post(url, form_data, {
        headers: {
          'content-type': 'multipart/form-data',
          'X-CSRFTOKEN': CSRF_TOKEN
        }
      }).then(res => {
        console.log(res.data);
      }).catch(err => console.log(err))
  };




    return (
        <Grid container spacing={6} justify="center" alignItems="center" direction="row" style={{marginTop:'3'}}>
            <Grid item lg={8} xs={11}>
            <Typography>Add new posts </Typography>
            <form  onSubmit={handlesubmit} >
            <TextField style={{margin:'5px'}} value={title} onChange={(e)=>setTitle(e.target.value)} multiline  fullWidth id="outlined-basic" label="Post Title" variant="outlined" />
            <TextField style={{margin:'5px'}} value={body} onChange={(e)=>setBody(e.target.value)} multiline fullWidth id="outlined-basic" label="Post Body" variant="outlined" />
            <Grid item xs={11} lg={8} style={{margin:'5px'}} >
                <Typography color="primary">Upload an Image </Typography>
                <input type="file" accept="image/png, image/jpeg"  onChange={(e)=>{setPicture(e.target.files[0])}}  />
                <input type="submit"/>

            </Grid>

         </form>

            </Grid>



      </Grid>
    )
}

export default Addpost


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Facing ErrorDetail(string=&#39;提交的数据不是文件。检查表单上的编码类型。&#39;, code=&#39;invalid&#39;) -Django Rest + React - Facing ErrorDetail(string='The submitted data was not a file. Check the encoding type on the form.', code='invalid') -Django Rest + React PHP:无法检查是否提交了表单 - PHP :unable to check if a form is submitted 检查表格的安全性。 - Check the security of form. 无法在React表单上输入我的第二个字段。 为什么会这样呢? - Unable to type into my second field on a React form. Why could this be happening? js删除提交的表单数据 - js deleting submitted form data 当尝试使用django Rest框架和REACT与Axios上传文件时,如何修复“没有提交文件。” - How to fix “No file was submitted.” when trying to upload a file with django Rest framework and REACT with Axios 从HTML表单使用Angular JS发布数据。 未捕获的错误:[$ injector:modulerr] - Post data with Angular JS from HTML form. Uncaught Error: [$injector:modulerr] 尝试将生成的PDF文件从React Js发送到Django-Rest Post请求时,未提交任何文件 - No file was submitted when try to send generated PDF file from React Js to Django-Rest Post request 使用js更新表单字段,但未在提交的数据中显示 - update form field with js but not showing in submitted data onunload-检查表单是否已提交 - onunload - Check if Form was submitted
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM