Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot upload files to django rest framework using react js

I'm using react Js to upload an image to django restframework. here I'm sending post request using fetch API.

Eapp.jsx

import React, { Component } from 'react';

class Eapp extends Component {
  constructor(props){
    super(props);
    this.state = {
      profilePic: null,
    };
    this.inpuElement = null;
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(e){
    this.setState({profilePic: e.target.files[0]});
  }
  handleSubmit(){
    let formData = new FormData();
    formData.append('profile_pic',this.state.profilePic);
    fetch('http://10.42.0.1:8000/auth/profile-pic/', {
      method: 'POST',
      headers: {
        Accept: 'application/json, text/plain, */*',
        'content-type': 'multipart/form-data',
      },
      body:formData,
    }).then(res => res.json())
      .then((data) => {
        console.log(data);
      })
      .catch(err => console.log(err));
  }

  render(){
      return(
        <div>
          <input
            type="file"
            multiple={false}
            ref={(input) => { this.inpuElement = input; }}
            accept=".jpg,.jpeg,.png"
            onChange={this.handleChange}
          />
          <button onClick={this.handleSubmit}>submit</button>
      </div>
    );
  }
}
export default Eapp;

error msg

Eapp.jsx:19 POST http://10.42.0.1:8000/auth/profile-pic/ 500 (Internal Server Error)
handleSubmit @ Eapp.jsx:19
callCallback @ react-dom.development.js:542
invokeGuardedCallbackDev @ react-dom.development.js:581
invokeGuardedCallback @ react-dom.development.js:438
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:452
executeDispatch @ react-dom.development.js:836
executeDispatchesInOrder @ react-dom.development.js:858
executeDispatchesAndRelease @ react-dom.development.js:956
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:967
forEachAccumulated @ react-dom.development.js:935
processEventQueue @ react-dom.development.js:1112
runEventQueueInBatch @ react-dom.development.js:3607
handleTopLevel @ react-dom.development.js:3616
handleTopLevelImpl @ react-dom.development.js:3347
batchedUpdates @ react-dom.development.js:11082
batchedUpdates @ react-dom.development.js:2330
dispatchEvent @ react-dom.development.js:3421
example:1 Failed to load http://10.42.0.1:8000/auth/profile-pic/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Eapp.jsx:30 TypeError: Failed to fetch

django

 views.py
    class ProfilePictureView(generics.CreateAPIView):
        permission_classes = (permissions.AllowAny,)
        serializer_class = ProfilePictureSerializer
        parser_classes = (parsers.FormParser,parsers.MultiPartParser, parsers.FileUploadParser, )

        def perform_create(self, serializer):
            print(self.request.FILES['profile_pic'])
            serializer.save(user=User.objects.get(pk=2))


models.py

class Person(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    profile_pic = models.ImageField(null=True, upload_to='media')
    face_encodings = models.BinaryField(null=True)
    def __str__(self):
        return str(self.user.first_name)


serializers.py

class ProfilePictureSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ['profile_pic','user']
        read_only_fields = ('user',)

class ProfilePictureSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ['profile_pic','user']
        read_only_fields = ('user',)

class ProfilePictureSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ['profile_pic','user']
        read_only_fields = ('user',)


raise MultiPartParserError('Invalid boundary in multipart: %s' % boundary.decode())
AttributeError: 'NoneType' object has no attribute 'decode'

I have included django cors headers, every other api route is working except this one. I've tried different methods of post request but still got the errors. It's not seems access to the server because every other route is working. I've tried MultiPart parser fileUpload parser in django but still got error status 400, 500 .

like image 951
Prakhil TP Avatar asked Mar 07 '23 23:03

Prakhil TP


1 Answers

try without content-type in header,it will help for sure.

like image 162
Avinash Thorat Avatar answered Apr 28 '23 01:04

Avinash Thorat