【问题标题】:Sending image and JSON simultaneously同时发送图像和 JSON
【发布时间】:2019-01-16 22:07:59
【问题描述】:

我想同时将 JSON 对象和图像从 react 传递给我的 django rest api。

我已经尝试了这个论坛和教程中的一些解决方案,但在我的情况下没有任何效果。以前我一直在状态字段上使用 JSON.stringify 并且有效,但我无法传递图像,现在我最终得到了这样的结果。

postData.js

    let formData = new FormData();
    const { title, description, image, ingredient, step } = this.state;
    formData.append('image', image);
    formData.append('title', title);
    formData.append('description', description);
    formData.append('ingredient', ingredient);
    formData.append('step', step);
    let conf = {
        method: 'post',
        body: formData,
        headers: new Headers({
            'Content-Type': 'multipart/form-data',
            'Accept': 'application/json'
        })
    };
    fetch('http://127.0.0.1:8000/api/', conf)
    .then(res => {
        this.props.history.push('/');
    })
    .catch(err=>{console.log(err)})

serializers.py

    class RecipeSerializer(serializers.ModelSerializer):
      ingredient = IngredientSerializer(many=True, required=False)
      step = StepSerializer(many=True, required=False)

      class Meta:
        model=models.Recipe
        fields=('id', 'title', 'description', 'image', 'ingredient', 'step', )

      def create(self, validated_data):
        ingredient_data = validated_data.pop('ingredient')
        step_data = validated_data.pop('step')
        recipe = models.Recipe.objects.create(**validated_data)
        for ingredient in ingredient_data:
           models.Ingredient.objects.create(recipe=recipe, **ingredient)
        for step in step_data:
           models.Step.objects.create(recipe=recipe, **step)
        return recipe

views.py

    class ListRecipes(generics.ListCreateAPIView):
      queryset = Recipe.objects.all()
      serializer_class = RecipeSerializer

    class DetailRecipe(generics.RetrieveUpdateDestroyAPIView):
      queryset = Recipe.objects.all()
      serializer_class = RecipeSerializer

我总是得到 POST http://127.0.0.1:8000/api/400 (Bad Request) 错误。

--编辑--

我更改了代码并创建了用于上传图像的新端点,从技术上讲它可以工作,但我正在尝试将图像和创建的配方 ID 附加到 FormData() 并且当我将它记录到控制台时它包含它们两者但是当我'在后端打印它只包含图像。

postData.js

    formData.append('id', this.state.id);
    formData.append('image', image, image.name);

    for(let key of formData.entries()){
        console.log(key);
    }
    let data = {
        method: 'post',
        body: formData,
        headers: new Headers({
            'Accept': 'application/json'
        })
    };
    fetch('http://127.0.0.1:8000/api/images/', data)
    .then(res => {
        console.log(res);
    })
    .catch(err=>{
        console.log(err);
    })

serializers.py

  class ImageSerializer(serializers.ModelSerializer):
    class Meta:
       model = models.Image
       fields = ('id', 'image', )

    def create(self, validated_data):
       print(validated_data)
       recipe = models.Recipe.objects.get(id=validated_data.id)
       image = models.Image.objects.create(recipe=recipe, **validated_data)
       return image

【问题讨论】:

  • 我认为最好为图像和 JSON 创建单独的端点。然后使用单独的 fetch 函数进行文件上传和发布 JSON。
  • 是的,我已经考虑过了,当然我可以做到,但老实说,我不太喜欢 DRF,而且我不知道如何进入第二个 fetch recipe 对象,图像应该是相关的。你能解释一下吗?或者在解释的地方提供链接?

标签: javascript django reactjs django-rest-framework


【解决方案1】:

您应该将 DRF MultiPartParser 添加到您的视图的 parser_classes

【讨论】:

  • 还是同样的错误。我还将 FormParser 添加到 parser_classes 和 encType="multipart/form-data" 以形成,它也没有工作。
  • 服务器是否引发代码引发任何异常?如果有,请发帖
  • 我记得它总是给出 Bad request at: /api/ 错误。我现在改变了结构,我几乎得到了它,但我遇到了一个问题。我对我的问题添加了编辑。
  • 如果你调试它,你会发现导致错误请求的原因。到时候修复会更容易
  • 客户端收到的响应通常包含错误信息的详细信息
猜你喜欢
  • 1970-01-01
  • 2015-04-26
  • 1970-01-01
  • 2020-12-15
  • 2019-07-23
  • 1970-01-01
  • 2012-01-08
  • 2019-03-09
  • 1970-01-01
相关资源
最近更新 更多