首页 > 解决方案 > 将图像从 React 上传到 Django 时出错

问题描述

我在 django 中有以下视图,我可以从 Postman 上传图像,但是从 React 上传时出现此错误。“KeyError:关键 profile_pic 不存在”

看法

class ProfilePictureUpload(APIView):
    """
    Endpoint to update Profile picture
    """

    parser_classes = (MultiPartParser, FormParser)
    permission_classes = [(permissions.IsAuthenticated & ProfilePagePermissions)]

    def put(self, request):
        print(f"request.data = {request.data.items()}, ")
        print(f"request.FILES = {dir(request.FILES.items())}")
        try:
            profile = Profile.objects.get(user__id=request.user.id)
            self.check_object_permissions(request, profile)
        except Exception as e:
            return Response(str(e), status=status.HTTP_404_NOT_FOUND)

        profile_pic_serializer = ProfilePicUpdateSerializer(profile, data=request.data)
        if profile_pic_serializer.is_valid():
            profile_pic_serializer.save()
            return Response(profile_pic_serializer.data)
        return Response(
            profile_pic_serializer.errors, status=status.HTTP_400_BAD_REQUEST
        )

串行器

class ProfilePicUpdateSerializer(serializers.ModelSerializer):
   """
   Separate endpoint for updating profile picture because submitting profile picture
   in a form along with other fields is not a good UX
   """

   class Meta:
       model = Profile
       fields = ["profile_pic"]

   def update(self, instance, validated_data):
       print(f"instance = {instance} \n validated data = {validated_data} ")
       instance.profile_pic = validated_data["profile_pic"]
       instance.save()
       return instance

我在这里打印经过验证的。这是 validated data = {'profile_pic': <InMemoryUploadedFile: Andrew Garfield.jpg (image/jpeg)>}. 当从邮递员那里尝试时。

从 React 尝试时它是空字典。

反应

function ProfilePicUpload(props) {
  let { profile_pic } = props;

  const [loading, setLoading] = useState(false);
  const [file, setFile] = useState();

  const handleSubmit = (e) => {
    console.log(file);
    e.preventDefault();
    const formData = new FormData();
    formData.append('profile_pic', file);
    console.log('formdata', formData);
    axiosInstance
      .put('users/profile-pic-upload/', formData, {
        headers: {
          'Content-Type':
            'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW',
        },
      })
      .then((response) => console.log(response))
      .catch((error) => console.log(error.response));
  };

  return (
    <div className='profile-update-form'>
      <h4>Profile Picture</h4>
      <div className='profile-pic-container'>
        <img src={profile_pic} className='profile-pic' />
        <form onSubmit={handleSubmit}>
          <input type='file' onChange={(e) => setFile(e.target.files[0])} />
          <button type='submit'>Upload file</button>
        </form>
      </div>
    </div>
  );
}

虚拟环境 - requirements.txt

asgiref==3.3.4
certifi==2020.12.5
cffi==1.14.5
chardet==4.0.0
coreapi==2.3.3
coreschema==0.0.4
cryptography==3.4.7
defusedxml==0.7.1
dj-database-url==0.5.0
Django==3.2.3
django-allauth==0.44.0
django-cors-headers==3.7.0
django-crispy-forms==1.11.2
django-rest-auth==0.9.5
django-rest-knox==4.1.0
django-rest-passwordreset==1.1.0
Django-Verify-Email==1.0.7
djangorestframework==3.12.4
djangorestframework-simplejwt==4.6.0
drf-yasg==1.20.0
gunicorn==20.1.0
idna==2.10
inflection==0.5.1
itypes==1.2.0
Jinja2==3.0.1
MarkupSafe==2.0.1
oauthlib==3.1.0
openapi-codec==1.3.2
packaging==20.9
Pillow==8.2.0
psycopg2==2.9.1
pycparser==2.20
PyJWT==2.1.0
pyparsing==2.4.7
python3-openid==3.2.0
pytz==2021.1
PyYAML==5.4.1
requests==2.25.1
requests-oauthlib==1.3.0
ruamel.yaml==0.17.9
ruamel.yaml.clib==0.2.2
simplejson==3.17.2
six==1.16.0
sqlparse==0.4.1
uritemplate==3.0.1
urllib3==1.26.4
whitenoise==5.2.0

请帮助解决问题。

标签: reactjsdjangomultipartform-data

解决方案


推荐阅读