Upload File in a folder without using submit button in Django

I am on a Django project and the scenario is that I want to save file in a folder without clicking on submit button. I am already saving the file in a folder with the help of submit button but now the scenario has changed and now I want to save file without clicking on submit button. Here are the details of my files:

views.py:

def compliance_check(request):`
 if request.method == 'POST':`
  uploaded_file = request.FILES['doc']`
  print(uploaded_file.name)`
  print(uploaded_file.size)`
  fs = FileSystemStorage()`
  fs.save(uploaded_file.name, uploaded_file)`
  messages.info(request, 'your file ' + uploaded_file.name + " has been uploaded successfully")
  return render(request, 'enroll/abc.html')

upload.html:

<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" id="file" name="doc">
<input type="submit" name = "doc" value="upload file" class="btn btn-warning btn-sm" disabled /> 
</form>

settings.py:

STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join('/home/t/Desktop/folder name')
MEDIA_URL = '/upload/'

urls.py:

path('compliance_check/', views.compliance_check, name='compliance check'),

Now the situation is that I am already saving file in a folder. But, now, I want to save file without clicking on submit button.

Try this in your html:

<form method="post" enctype="multipart/form-data" name="myform">
{% csrf_token %}
<input type="file" id="file" name="doc" onchange="document.myform.submit()">
</form>

This will submit the form, if the user closes the file selection dialog (I assume, this is what you want). Chose a better name for your form than "myform".

Back to Top