Samudranil Roy
Samudranil Roy

Reputation: 221

In Django how to getbinary field data from POST form

I have one HTML file, where I am using one image upload button. Now this image is stored in the MySql database as Blob. I need to get or read this image data somehow in Django through post method. Can anyone please help how to do?

Icon is defined like :

icon = models.BinaryField(null=True)

My Html:

 <input type="file" id="toolicon" accept="image/*" data-type='image'  >
<button id="OpenImgUpload" style="margin-left: 100px">Image Upload</button>

In JQuery:

$('#OpenImgUpload').click(function(){ $('#toolicon').trigger('click'); });

Image:

Html look

Now I want to get this file as Binary Field data. Till now I have used :

tool_icon = request.POST('toolicon', '')
tool_icon = request.POST.get('toolicon', '')
tool_icon = base64.b64encode('toolicon', '')

Nothing works ... Can any one please help me.

Upvotes: 1

Views: 1111

Answers (1)

Will Keeling
Will Keeling

Reputation: 23014

Uploaded files are contained in request.FILES with the key corresponding to the name attribute on the input element.

So you should add a name attribute to your input:

<input type="file" name="toolicon" ...

And then access the data using request.FILES:

tool_icon = request.FILES.get('toolicon', '')

The request must have a content type of multipart/form-data which you should set on your form:

<form enctype="multipart/form-data" ...

Upvotes: 1

Related Questions