4👍
I have been working on a similar problem and here’s how I managed to make it work.
First of all, you should not use JSON object to send files to the server. So this part won’t work
body: JSON.stringify(data_elements)
There are several ways to encode an image to be able to send it to the server (like encoding it to base64) but the easiest way that I found is just to use the FormData() object
Here’s a snippet of my code
let formData = new FormData()
formData.append('image', e.target.files[0])
formData.append('account', currentAccount.username)
fetch('/api/post/add', {
method: 'POST',
body: formData
}).then( response => response.json())
.then( response => {
console.log(response)
})
You can do async/await instead of promises but you get the idea.
IMPORTANT NOTE:
The content type when using FormData is 'Content-Type': 'multipart/form-data'
however, you should NOT define ANY content type in this particular request cause it will mess it up. Let the browser define the content type. Why? Read the reason here.
The backend Django part.
Again, we’re not dealing with JSON so you can’t use
data = json.loads(request.body.decode("utf-8"))
Here’s how it should look like:
def add_image(request):
if request.user.is_authenticated:
if request.method == 'POST':
image = request.FILES.get("image")
account = request.POST.get("account")