javascript 如何上传多张图片到Django?

iibxawm4  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(178)

我试图从客户端发送一些数据(react native),其中包括一些图像,所以我将它们附加到formdata并通过post请求成功发送,但我在弄清楚如何在服务器端处理它时遇到了麻烦。
我的React代码:

const post = async () => {
    const token = await getToken();
    const [description, setDescription] = useState('');

    const formData = new FormData();

    images.forEach((image) => {
      formData.append(`images`, {
        uri: image,
        type: 'image/jpeg',
        name: image,
      });
    });
    formData.append('description', description);
    console.log('formdata:', formData);

    try {
      await axios.post(URL, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: token,
        },
      });
    } catch (e) {
      console.log(e);
    }
  };

当我在客户端控制台记录表格数据时,我得到:

formdata: [["images", {"name": "/Library/Developer/CoreSimulator/Devices/123.jpg", "type": "image/jpeg", "uri": "/Library/Developer/CoreSimulator/Devices/123.jpg"}], ["images", {"name": "/Library/Developer/CoreSimulator/Devices/456.jpg", "type": "image/jpeg", "uri": "/Library/Developer/CoreSimulator/Devices/456.jpg"}], ["description", "Test"]]

在我的服务器端(django/drf):
models.py:

class Post(models.Model):
    user_id = models.ForeignKey(
        User, on_delete=models.CASCADE, default=None
    )
    images = models.FileField(
        max_length=3000, default=None, null=True, blank=True, upload_to='media/post_images')
    description = models.TextField(null=False, default=None)
    date = models.DateTimeField(editable=False, auto_now_add=True)

serializers.py:

class PostSerializer(serializers.ModelSerializer):
    images = serializers.FileField()

class Meta:
    model = Post
    fields = "__all__"

views.py

class PostView(APIView):
    serializer_class = PostSerializer
    parser_classes = (MultiPartParser, FormParser)

def post(self, request, format=None):

    form_data = request.data

    images = form_data.get('images')
    description = form_data.get('description')
    user_id = self.request.user

    print(form_data)

    post = Post.objects.create(
        images=images, description=description, user_id=user_id)

    post.save()

    serializer = PostSerializer(post)

    return Response(serializer.data, status=status.HTTP_201_CREATED)

当我在python中打印form_data时,我得到:

<QueryDict: {'0': ['images'], '1.uri': ['/Library/Developer/CoreSimulator/Devices/123.jpg'], '1.type': ['image/jpeg'], '1.name': ['/Library/Developer/CoreSimulator/Devices/123.jpg'], '1.0': ['images'], '1.1.uri': ['/Library/Developer/CoreSimulator/Devices/456.jpg'], '1.1.type': ['image/jpeg'], '1.1.name': ['/Library/Developer/CoreSimulator/Devices/456.jpg'], '2.0': ['description'], '2.1': ['Test']}>

如何提取数据并将其保存到数据库?

lb3vh1jj

lb3vh1jj1#

Django正在为您处理。您可以尝试通过以下方式访问您的图像:

request.FILES.getlist("images")

这将为您提供一个在提交的表单中找到的所有图像的列表。

相关问题