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?

wahyu
  • 1,679
  • 5
  • 35
  • 73
  • Are you using django-rest-framework or just Django as a monolith? You can have a look here -> https://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. – mutantkeyboard Mar 18 '21 at 08: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 ? – wahyu Mar 18 '21 at 14:22

1 Answers1

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.

AnnieFromTaiwan
  • 3,845
  • 3
  • 22
  • 38
mutantkeyboard
  • 1,614
  • 1
  • 16
  • 44
  • 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 – wahyu Mar 22 '21 at 01:14