我正在一个项目(在Django中)中创建一个页面,以添加有关文件的数据信息,然后添加文件本身。
单击“更多数据集”按钮时,它将添加另一个字段以上传另一个文件。
可以一次性添加最终用户所需数量的文件。
我需要的是一旦单击“上传数据集”并应该显示单个进度条,就上传所有附件。
到目前为止,我已经看完了多个教程,但是使用Vitor Freitas的教程有点接近。
JS代码:
$(function(){
/*$("#add_new_dataset").click(function(){
$(".file").click();
});*/
$(".file").fileupload({
dataType: 'json',
sequentialUploads: true, /* Send the files one by one */
start: function(e){ /* When the upload process starts, show the modal */
$("#modal-progress").modal("show");
},
stop: function(e){ /* When the upload progress finalizes, hide the modal */
$("#modal-progress").modal("hide");
},
progressall: function(e, data){ /* Update the progress bar */
var progress = parseInt(data.loaded / data.total * 100, 10),
strProgress = progress + "%";
$(".progress-bar").css({"width": strProgress});
$(".progress-bar").text(strProgress);
},
done: function(e, data){
if(data.result.is_valid){
$("#gallery tbody").prepend(
"
" + data.result.name + "");
}
}
})
});
模板代码:
{% csrf_token %}
User Name :
Data-set :
Creation Date :
Beam Line:
Data-set file:
Submit Data-set
我该怎么办?我不太擅长AJAX,但是看不到任何可将数据发送到服务器端的代码。是这样还是我缺少什么?请忽略我对这个话题的无知,并感谢大家。
编辑:
基于一些答案,JS代码已被重写。
document.getElementById('add_new_dataset').onclick = function() {
$(this).preventDefault();
console.log('Files uploading begin');
form_data = new FormData();
const files = document.getElementsByName('file');
let count = 0;
for(let i = 0; i < files.length; i++){
count++;
form_data.append("file", files[i]);
}
$.ajax({
url: "/add_data_sets",
dataType: 'json',
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function(files, response, xhr, pd){
$('.file').show();
if(files.status != false){
$('.progress-bar').val('/location/' + files.filename);
var fileData = files.filename;
console.log('Files uploading...');
}
else{
alert(files.filename);
}
},
/*xhrFields: {
onprogress: function(e) {
if(e.lengthComputable) {
let percentCompleted = e.loaded / evt.total;
pBar.style.width = percentComplete;
pBar.innerHTML = percentComplete + "%";
console.log('Percent complete : ' + percentComplete);
}
}
}*/
xhr: function(){
let xhr = $.ajaxSettings.xhr();
xhr.upload.onprogress = function(e) {
let percentCompleted = e.loaded / evt.total * 100;
pBar.style.width = percentComplete;
pBar.innerHTML = percentComplete + "%";
console.log('Percent complete : ' + percentComplete);
};
return xhr;
}
});
//});
};
这只是上传代码块。从客户端到服务器端的数据发送工作正常,但由于代码运行时未触发“ console.log”调用而令人怀疑。数据是否以某种方式正常提交,并且此代码没有执行任何操作。
EDIT2:新的JS函数:
function upload() {
console.log('Upload function begins');
let pBar = document.getElementsByClassName('progress-bar')[0],
progressWindow = document.getElementById('modal-progress'),
formData = new FormData(document.forms.form),
xhr = new XMLHttpRequest(),
percent = 0;
console.log('Form Data created');
// Start upload
xhr.upload.onloadstart = function() {
//$('#modal-progress').hide().fadeIn();
//progressWindow
};
// Track upload progress
xhr.upload.onprogress = function(event) {
percent = parseInt(event.loaded / event.total * 100);
pBar.innerHTML = percent + "%";
pBar.style.width = percent + "%";
//console.log(percent + '% completed');
//console.log('Uploaded event.loaded of event.total');
};
// Report if ends with an error
xhr.upload.onerror = function() {
console.log('An error has occurred')
};
// Track completion: Both successful or not
xhr.upload.onloadend = function() {
//$('#modal-progress').fadeOut().hide();
console.log('Upload complete with or without error ' + xhr.status);
};
// Track progress: Triggered on successful completion
xhr.upload.onload = function() {
console.log('Uploading complete');
progressWindow.hidden = True;
};
xhr.open("POST", "{% url 'add_data_sets' %}", true);
// The 'setRequestHeader' function can only be called when xhr is opened.
//xhr.setRequestHeader('csrfmiddlewaretoken', '{{ csrf_token }}');
//xhr.setRequestHeader('test-info', 'something');
xhr.setRequestHeader('Content-Type', 'application/gzip');
xhr.send(formData);
}
该功能现在可以正常工作。它发送数据完全正常,但是在开发服务器控制台屏幕上我收到此错误。
Forbidden (CSRF token missing or incorrect.): /accounts/add_data_set/
[22/Feb/2020 15:36:06] "POST /accounts/add_data_set/ HTTP/1.1" 403 2513
I even checked logged the POST data being send to the server and it does contain the csrf token
I'm kind of confused. Is this an issue?
解决方案
If you have any fileuploader plugin their documentations will have everything, or if you want normal file upload input you can post them by binding file input to form data and then post on action which will manipulate form data and save images, then you can return save image and display, this way you can achieve simple ajax upload.
var form_data = new FormData();
var totalFiles = document.getElementById('file').files.length;
var count = 0;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById('file').files[i];
count++;
form_data.append("file", file);
}
$.ajax({
url: "/uploadingaction",
dataType: 'json',
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function (files, response, xhr, pd) {
$('yourloaderid').hide();
if (files.status != false) {
$('#displayid').val('/location/' + files.filename);
var filedata = files.filename;
} else {
alert(files.filename);
}
}
})