#django #django-views
Вопрос:
У меня проблема с django, и она заключается в том, что я не могу обрабатывать файлы, которые загружаю в загрузчик файлов.
Загрузчик файлов, который я использую, — это тот, который мы можем загрузить в Bootstrap Studio под названием «Загрузка с помощью перетаскивания нескольких файлов для ввода», код которого (изменен с помощью csrf_token, необходимого для его работы в django) выглядит следующим образом:
HTML
<div id="backdrop" class="backdrop backdrop-transition backdrop-dark">
<div class="text-center w-100" style="position: absolute;top: 50%;">
<div class="bg-light border rounded border-success shadow-lg m-auto" style="width: 150px;height: 150px;"><i class="fa fa-upload d-block p-4" style="font-size: 50px;"></i><span>Drop file to attach</span></div>
</div>
</div>
<div class="jumbotron pt-1">
<div class="alert alert-success invisible mt-5" role="alert"><span id="notify"></span></div>
<h1>Subir Ficheros<br></h1>
<p><label for="form-files"><a class="btn btn-secondary btn-sm" role="button">Seleccione ficheros</a></label>amp;nbsp;o arrastre los ficheros a cualquier lugar de la página.<br></p>
<p id="filecount"><br></p>
<div id="list"></div>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" id="form-files" class="invisible" name="files" multiple="">
<button class="btn btn-outline-primary btn-block" type="submit">Procesar</button>
<button class="btn btn-danger mt-5" type="reset" onclick="clearFiles()">Reiniciar</button>
</form>
</div>
<div class="text-center bg-light border rounded border-dark shadow-lg p-3"><img id="image_preview" width="100">
<div><button class="btn btn-warning btn-sm m-3" onclick="previewClose()">Cerrar</button></div>
</div>
JS
var dt_allowed=false,readerfiles,drop,fileCount,fileinput,backdrop,notify,list,listwait,listsync=false,image_preview;
addEventHandler(window, 'load', function () {
init_elements();
init_fileinput();
if (window.FileReader amp;amp; window.DataTransfer) {
init_datatransfer();
} else {
notify_msg('Your browser does not support the HTML5 FileReader.<br/> Drag and drop is disabled.');
}
listFiles();
});
function init_elements() {
drop = document, // Drop Target
fileCount = document.getElementById('filecount');
fileinput = document.getElementById('form-files');
backdrop = document.getElementById('backdrop');
list = document.getElementById('list');
notify = document.getElementById('notify');
image_preview = document.getElementById('image_preview');
previewClose();
}
function init_fileinput() {
addEventHandler(fileinput,'change', function (e) {
cancelDefault(e);
if (!listsync) {
addFiles(fileinput.files);
}
return false;
});
}
function init_datatransfer() {
dt_allowed=true;
readerfiles = new DataTransfer();
addEventHandler(drop, 'dragover', function (e) {
cancelDefault(e);
backdrop.classList.add('visible');
return false;
});
addEventHandler(drop, 'dragleave', function (e) {
cancelDefault(e);
backdrop.classList.remove('visible');
return false;
});
addEventHandler(drop, 'dragenter', cancelDefault);
addEventHandler(drop, 'drop', function (e) {
cancelDefault(e);
backdrop.classList.remove('visible');
addFiles(e.dataTransfer.files)
});
}
function cancelDefault(e) {
e=e||window.event;
if (eamp;amp;e.preventDefault) {
e.preventDefault();
}
return false;
}
function addEventHandler(obj, evt, handler) {
if (obj.addEventListener) {
obj.addEventListener(evt, handler, false);
} else if (obj.attachEvent) {
obj.attachEvent('on' evt, handler);
} else {
obj['on' evt] = handler;
}
}
function clearFiles(){
fileinput.value='';
if (dt_allowed) readerfiles = new DataTransfer();
previewClose();
notify_msg('Ficheros eliminados');
listFiles();
}
function addFiles(files) {
files_text = 'Fichero(s) añadido(s):</br>';
for (var i=0,l=files.length;i<l;i ) {
files_text =' ' files[i].name '</br>';
if (dt_allowed) readerfiles.items.add(files[i]);
}
notify_msg(files_text);
listFiles();
}
function remFile(file_i) {
if (!dt_allowed) return;
previewClose();
file_i=parseInt(file_i);
if (file_i<0||readerfiles.files.length-1<file_i) return;
notify_msg('File removed:</br>' readerfiles.files[file_i].name);
readerfiles.items.remove(file_i);
listFiles();
}
function listFiles(w=true) {
if (w||listwait) {
if (listwait) clearTimeout(listwait);
listwait=setTimeout(function(){ listwait=null; listFiles(false); },200);
return;
}
var thelist=dt_allowed? readerfiles : fileinput;
listsync=true;
fileCount.innerHTML=thelist.files.length ' ficheros: '
list.innerHTML='';
for (var i=0,l=thelist.files.length;i<l;i ) {
var a = document.createElement('button');
a.setAttribute('type','button');
a.setAttribute('class','close');
a.setAttribute('aria-label','Close');
a.setAttribute('onclick','remFile(' i ')');
var s = document.createElement('span');
s.setAttribute('aria-hidden','true');
s.textContent='×';
a.appendChild(s);
list.appendChild(a);
var newFile = document.createElement('a');
newFile.innerHTML = thelist.files[i].name ' size ' thelist.files[i].size 'B';
newFile.setAttribute('href','#');
newFile.setAttribute('onclick','previewFile(' i ')');
list.appendChild(newFile);
list.appendChild(document.createElement('br'));
//var img = document.createElement("img");
//img.file = readerfiles.files[i];
//img.src = bin;
//img.width=50;
//list.appendChild(img);
}
if (dt_allowed) fileinput.files=readerfiles.files;
listsync=false;
}
function previewClose() {
image_preview.parentElement.classList.add('invisible');
}
function previewFile(file_i) {
previewClose();
if (!dt_allowed) return;
file_i=parseInt(file_i);
if (file_i<0||readerfiles.files.length-1<file_i) return;
const reader = new FileReader();
if (!['png','svg','gif','jpg','jpeg','tiff'].includes(readerfiles.files[file_i].name.split('.',-1).pop().toLowerCase())) return;
reader.addEventListener('load',function(){
previewFileReader(reader.result);
},false);
reader.readAsDataURL(readerfiles.files[file_i]);
}
function previewFileReader(bin) {
image_preview.src=bin;
image_preview.parentElement.classList.remove('invisible');
}
function notify_msg(m) {
notify.innerHTML=m;
notify.parentElement.classList.remove('invisible');
}
I’m trying to process the files uploaded to a directory inside the project, just like in the video «Introduction — Django File Upload Tutorial — Part 1» by Victor Freitas (https://www.youtube.com/watch?v=Zx09vcYq1oc) [Minute: 4:55] with the small nuance that I want to upload several files at the same time and not just one, so I am iterating over the uploaded files.
DJANGO — views.py
[...]
def fileUploader(request):
context = {
'title': 'File Uploader'
}
if request.method == 'POST':
fs = FileSystemStorage()
for file in request.FILES.getlist('files'):
print(file.name)
print(file.size)
name = fs.save(file.name, file)
url = fs.url(name)
print(url)
return render(request, 'site/fileUploader.html', context)
[...]
Когда я выполняю его, я не получаю никаких выходных данных, напечатанных в консоли (где я должен получать, по крайней мере, имя, размер и URL каждого загруженного файла), только "POST /fileUploader HTTP/1.1" 200 4841
петицию, когда я нажимаю кнопку Отправить формы.
Что происходит не так? Заранее спасибо