1

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.". When I use Django RF browsable API I can successfully add images. Will this be a problem from frontend then ?

VIEWS.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.

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>)

1 Answer 1

3

Found the answer, 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


Sign up to request clarification or add additional context in comments.

1 Comment

When i use e.target.files[0] i get the following error Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.