【问题标题】:Error: Invalid data. Expected a dictionary, but got InMemoryUploadedFile错误:无效数据。需要一本字典,但得到了 InMemoryUploadedFile
【发布时间】:2022-02-05 17:43:22
【问题描述】:

尝试从 react 上传多张图片到 django rest api 时出现上述错误。 这是我的 django 视图代码:

def post(self, request, *args, **kwargs):
    posts_serializer = PostSerializer(data=request.FILES.getlist('image[]'), many=True)
    print(posts_serializer)

    if posts_serializer.is_valid():
        posts_serializer.save()
        return Response(posts_serializer.data, status=status.HTTP_201_CREATED)
    else:
        print('error', posts_serializer.errors)
        return Response(posts_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

这是来自 posts_serializer 的打印:

PostSerializer(data=[<InMemoryUploadedFile: 1PSM Logo.png (image/png)>, <InMemoryUploadedFile: Microsoft-Azure-Fundamentals.png (image/png)>, <InMemoryUploadedFile: DP-900_ProductImage-1.png (image/png)>], many=True):
            id = IntegerField(label='ID', read_only=True)
            image = ImageField(max_length=100)

感谢任何帮助。

【问题讨论】:

  • 删除getlist('image[]')并尝试
  • 你能给我们看看你的 PostSerializer 吗? (使用 DRF,您应该使用 request.data,而不是 request.FILES)
  • @Ahtisham 谢谢,我删除了 getlist() 并将 FILES 切换为数据。它现在运行没有错误,但文件没有上传到文件夹中。我还在控制台中收到“未找到:/cgi-bin/ Broken pipe from ('127.0.0.1', 59366)”。

标签: reactjs django django-rest-framework


【解决方案1】:

所以我终于用不同的方式让它工作了:

def post(self, request, *args, **kwargs):
    if request.method == "POST":
        allimages = request.FILES.getlist('images')
        for oneimage in allimages:
            Post.objects.create(images=oneimage)
        return Response(status=status.HTTP_201_CREATED)
    return Response(status=status.HTTP_400_BAD_REQUEST)

class Post(models.Model):
images = models.FileField(upload_to='post_images', default='')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 2023-01-01
    • 2021-08-31
    • 2021-07-20
    • 1970-01-01
    相关资源
    最近更新 更多