1

I am new in python and django, right now I would like to upload an image from postman (content type: form-data) and then save it in server. So far I have doing this

@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)

so the flow is: upload image from postman and then directory 'media' will be created and the image will be stored there so far I have been following this https://www.geeksforgeeks.org/python-uploading-images-in-django/ but I don't know how to try it in postman, anyone knows step by step to save image file to server in django?

2
  • Are you using django-rest-framework or just Django as a monolith? You can have a look here -> stackoverflow.com/a/59295770/1737811 to see how it's done with POSTMAN. Basically you need to select option binary. And from there you can handle your image. And you can do it multiple ways. Commented Mar 18, 2021 at 8:54
  • @mutantkeyboard I am not using django-rest-framework, just using django as monolith. I take a look to your link that you have given and I am little bit confuse about how to declare it inside urls.py. Did you have any source to do it in django as monolith ? Commented Mar 18, 2021 at 14:22

1 Answer 1

2

Here is the code, but keep in mind that I didn't test it, since I wrote it on the fly.

I also assume you use Python3.2+, since you won't be able to use os.makedirs with exist_ok flag.

If you're using Python3.5+, you can also replace that code with something like Pathlib which can create folder, but won't raise an exception like so:

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

and you can replace the os.makedirs in the code bellow with this call in that case.

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)

Now, that's an easy part.

For Postman, simply follow this answer -> https://stackoverflow.com/a/49210637/1737811

Hope this answers your question.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi sorry for my late reply, I just take a look to your answer today, and I will try it and let you know the result

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.