<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"></script>
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"></script>
</head>
<style>
.not-visible{
display: none;
}
</style>
<body>
<form action="" method="post" id="upload_form">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Upload" class="btn btn-primary">
<button type="submit" id="cancel" aria-placeholder="cancel">cancel</button>
</form>
<div class="container not-visible progress" id="progress">
</div>
<script>
const uploadForm = document.getElementById('upload_form');
const input_file = document.getElementById('id_image');
const progress_bar = document.getElementById('progress');
const cancel=document.getElementById('cancel')
$("#upload_form").submit(function(e){
e.preventDefault();
$form = $(this)
var formData = new FormData(this);
const media_data = input_file.files[0];
if(media_data != null){
console.log(media_data);
progress_bar.classList.remove("not-visible");
}
$.ajax({
type: 'POST',
url:'/',
data: formData,
dataType: 'json',
beforeSend: function(){
},
xhr:function (){
const xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', e=>{
if(e.lengthComputable){
const percentProgress = (e.loaded/e.total)*100;
console.log(percentProgress);
progress_bar.innerHTML = `<div class="progress-bar progress-bar-striped bg-success"
role="progressbar" style="width: ${percentProgress}%" aria-valuenow="${percentProgress}" aria-valuemin="0"
aria-valuemax="100"></div>`
}
});
cancel.addEventListener('click',(xhr.abort));
return xhr
},
success: function(response){
console.log(response);
uploadForm.reset()
progress_bar.classList.add('not-visible')
},
error: function(err){
console.log(err);
},
cache: false,
contentType: false,
processData: false,
});
});
</script>
</body>
</html>