'Sending image from front end(JavaScript) to backend(Django)
I have a image at the front end and I want to send it to the backend. I have simple JavaScript at the front end and Django-python at the backend. I have tried dozens of different methods and spent weeks but I am not able to figure this out. Can you guys suggest how can I achieve this on front end(sending part) and backend(receiving part). A piece of code with an advice would be really appreciated. I am using function based views on the backend. Can someone help me out with the backend code (if the front end code is right) to handle incoming from the front end. Because I have first converted the image file to base 64 stream in order to send it to the backend through fetch api.
Front end code:
const { snippet, transform } = anno.getImageSnippetById(annotation.id) //this function returns a DOM canvas element in snippet variable
const base64Canvas = snippet.toDataURL("image/jpeg").split(';base64,')[1]; //converting into a base64 stream
fetch(url1,{
method:'POST',
headers:{
'Content-type':'application/json',
'X-CSRFToken':csrftoken,
},
body: {'snippet':base64Canvas}
})
Backend code:
def snippetCreate(request):
serializer = Annotated_SnippetsSerializer(data=request['snippet'])
image = base64_to_image(base64_string=serializer.data)
img = Annotated_Snippets(asnippet=image)
img.save()
return Response({'success':'success'}) ```
base64_to_image:
```def base64_to_image(base64_string):
format, imgstr = base64_string.split(';base64,')
ext = format.split('/')[-1]
return ContentFile(base64.b64decode(imgstr), name=uuid.uuid4().hex + "." + ext) ```
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
