How to upload a file on click of a button in Django?
I have a requirement to upload a zip file with the click of an upload or save button. Then, when the user clicks on the "run" button, the uploaded file should get processed.
I created a simple form and could write code to upload a file when the submit button was clicked, as shown below.
if request.method=='POST':
upload_request=UploadFile()
upload_request.file=request.FILES['file_upload']
upload_request.save()
Template:
<form method="post" enctype="multipart/form-data">
{% csrf_token%}
<input type="file" required name="file_upload" id="choose_upload_file" value="" accept=".zip,.rar,.7z,.gz,"></br>
<input type="submit" class="btn btn-secondary btn-block" value="upload" id="file_upload1">
</form>
But how do I have a save functionality (a file should be uploaded) before submitting the form?
I am new to Django. Please give me some insights.
#try this
from django.shortcuts import render, redirect
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
def upload_zip_file(request):
if request.method == 'POST':
file = request.FILES['file']
if (file.name.endswith('.zip') or file.name.endswith('.rar') or
file.name.endswith('.7z') or file.name.endswith('.gz')):
path = default_storage.save('tmp/' + file.name, ContentFile(file.read()))
return redirect('success')
return render(request, 'upload.html')