Below is the code to handle the file limit from backend:
@app.route('/upload', methods=["POST","GET"])
def upload():
if request.method == "POST" and 'photo' in request.files:
uploaded_photos = request.files.getlist('photo')
if len(uploaded_photos) > 2:
error = "You are only allowed to upload a maximum of 2 files"
return render_template("upload.html", error=error)
else:
for photo in uploaded_photos:
photos.save(photo)
return 'saved'
else:
return render_template("upload.html")
Need to specify multiple attribute in the input field of the file to allow multiple images to be uploaded at a time
{% if error %}
<p class=error><strong>Error:</strong> {{ error }}</p>
{% endif %}
<form action="upload" method="POST" enctype="multipart/form-data">
<div class="custom-file">
<label for="customFile">Choose Cover Photo --Optional--</label>
<br>
<input type="file" name="photo" id="customFile" multiple>
<input type = "submit" value = "submit">
</div>
</form>
You can handle it in frontend using jquery. Below is the code.
$(function(){
$("input[type = 'submit']").click(function(){
var $fileUpload = $("input[type='file']");
if (parseInt($fileUpload.get(0).files.length) > 2){
alert("You are only allowed to upload a maximum of 2 files");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="POST" enctype="multipart/form-data">
<div class="custom-file">
<label for="customFile">Choose Cover Photo --Optional--</label>
<br>
<input type="file" name="photo" id="customFile" multiple>
<input type = "submit" value = "submit">
</div>
</form>
CLICK HERE to find out more related problems solutions.