开发者问题收集

无法使用 react js 将文件上传到 django rest framework

2018-02-05
8110

我正在使用 react Js 将图像上传到 django restframework。 在这里我使用 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;

错误消息

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'

我已经包含了 django cors 标头,除了这个之外,其他所有 api 路由都正常工作。我尝试了不同的发布请求方法,但仍然收到错误。 似乎无法访问服务器,因为其他所有路由都在正常工作。 我在 django 中尝试了 MultiPart 解析器 fileUpload 解析器,但仍然收到错误状态 400、500。

2个回答

尝试在标题中不使用 content-type,这肯定会有帮助。

Avinash Thorat
2018-02-05

在 handleSubmit 函数中尝试使用

"Content-Type":"multipart/form-data"

Srikant
2019-07-09