使用Django api将图像文件保存到服务器的步骤

2024-04-26 22:26:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python和django新手,现在我想从postman上传一个图像(内容类型:表单数据),然后将其保存在服务器中。到目前为止,我一直在做这件事

@csrf_exempt
def detector(request):
    data = {"success": False}
    if request.method == "POST":
        print("oke0")
        # check to see if an image was uploaded
        if request.FILES.get("image", None) is not None:
            ...# here I would like to save the image
        else:
            return JsonResponse(data)
    return JsonResponse(data)

因此,流程是:从邮递员上传图像,然后创建“媒体”目录,并将图像存储在那里 到目前为止,我一直在关注这个https://www.geeksforgeeks.org/python-uploading-images-in-django/,但我不知道如何在postman中尝试,有人知道如何逐步将图像文件保存到django中的服务器吗


Tags: todjango图像image服务器none类型内容
1条回答
网友
1楼 · 发布于 2024-04-26 22:26:59

这是代码,但请记住,我没有测试它,因为我是动态编写的

我还假设您使用Python3.2+,因为您将无法使用带有exist_ok标志的os.makedirs

如果您使用的是Python3.5+,您还可以将该代码替换为Pathlib之类的代码,它可以创建文件夹,但不会引发如下异常:

import pathlib
pathlib.Path('save_path').mkdir(parents=True, exist_ok=True) 

在这种情况下,您可以用这个调用替换下面代码中的os.makedirs

import os
import uuid

@csrf_exempt
def detector(request):
    data = {"success": False}
    if request.method == "POST":
        print("oke0")
        if request.FILES.get("image", None) is not None:
            #So this would be the logic
            img = request.FILES["image"]
            img_extension = os.path.splitext(img.name)[1]

            # This will generate random folder for saving your image using UUID
            save_path = "static/" + str(uuid.uuid4())
            if not os.path.exists(save_path):
                # This will ensure that the path is created properly and will raise exception if the directory already exists
                os.makedirs(os.path.dirname(save_path), exist_ok=True)

            # Create image save path with title
            img_save_path = "%s/%s%s" % (save_path, "image", img_extension)
            with open(img_save_path, "wb+") as f:
                for chunk in img.chunks():
                    f.write(chunk)
            data = {"success": True}
        else:
            return JsonResponse(data)
    return JsonResponse(data)

现在,这是一个简单的部分

对于邮递员,只需遵循以下答案->https://stackoverflow.com/a/49210637/1737811

希望这能回答你的问题

相关问题 更多 >