Reputation: 49
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/',{})
Upvotes: 0
Views: 1165
Reputation: 61
This is for the future me or someone who might have the same issue.
Make sure to respect the correct headers while using requests lib and sending files.
I follow the code and nothing work because we use remote models, so we have constructors and the headers dict was setting another 'content type'.
So if you need to set the token for the api call, you can use it like this:
getFile = request.FILES['form-data-name'].file.getvalue()
file = {'form-data-name': getFile,} #The other api get this field
self.response = requests.post(
f'{self.service}/resource/{pk}/action/',
headers={'Authorization': f'Bearer {self.token}'},
files=file
)
Upvotes: 1