'How to pass inMemoryUploadedFile into an api

I want to pass user uploaded images into an api from my view I have this form which submits a file into view

 <form action="http://127.0.0.1:8000/handler/" method="POST" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
</form>

I want to again send this file into an api but I can't do it directly, I think i must convert the file into string and pass to the api. Anybody have any idea on how to do it

@csrf_exempt
def handler(request):
    if request.method == 'POST':
        file = request.FILES['file']
        res = requests.post('http://192.168.1.68:8000/endpoint/',{})


Solution 1:[1]

If have to convert the file into string, you can use file.read(). But this is not recommended?if the uploaded file is huge it can overwhelm your system if you try to read it into memory.

For better practice, you should use TemporaryUploadedFile and open a stream to send any content:

# file handle by "TemporaryUploadedFile" already
file = request.FILES['file']
res = requests.post('http://192.168.1.68:8000/endpoint/', {
    "file": open(file.temporary_file_path(), 'rb'),
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cidos