DropZonejs: Отправить форму без файлов
Я успешно интегрировал dropzone.js в существующую форму. Эта форма размещает вложения и другие входы, такие как флажки и т.д.
Когда я отправляю форму с вложениями, все входы отправляются должным образом. Однако я хочу, чтобы пользователь мог отправить форму без каких-либо вложений. Dropzone не разрешает подачу формы, если нет вложения.
Кто-нибудь знает, как я могу переопределить это поведение по умолчанию и представить форму dropzone.js без каких-либо вложений? Спасибо!
$( document ).ready(function () {
Dropzone.options.fileUpload = { // The camelized version of the ID of the form element
// The configuration we've talked about above
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 50,
maxFiles: 50,
addRemoveLinks: true,
clickable: "#clickable",
previewsContainer: ".dropzone-previews",
acceptedFiles: "image/*,application/pdf, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.openxmlformats-officedocument.spreadsheetml.template, application/vnd.openxmlformats-officedocument.presentationml.template, application/vnd.openxmlformats-officedocument.presentationml.slideshow, application/vnd.openxmlformats-officedocument.presentationml.presentation, application/vnd.openxmlformats-officedocument.presentationml.slide, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.openxmlformats-officedocument.wordprocessingml.template, application/vnd.ms-excel.addin.macroEnabled.12, application/vnd.ms-excel.sheet.binary.macroEnabled.12,text/rtf,text/plain,audio/*,video/*,.csv,.doc,.xls,.ppt,application/vnd.ms-powerpoint,.pptx",
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
// Listen to the sendingmultiple event. In this case, it the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("successmultiple", function(files, response) {
window.location.replace(response.redirect);
exit();
});
this.on("errormultiple", function(files, response) {
$("#notifications").before('<div class="alert alert-error" id="alert-error"><button type="button" class="close" data-dismiss="alert">×</button><i class="icon-exclamation-sign"></i> There is a problem with the files being uploaded. Please check the form below.</div>');
exit();
});
}
}
});
Ответы
Ответ 1
Используйте следующее:
$('input[type="submit"]').on("click", function (e) {
e.preventDefault();
e.stopPropagation();
var form = $(this).closest('#dropzone-form');
if (form.valid() == true) {
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
} else {
myDropzone.uploadFiles([]); //send empty
}
}
});
Ссылка: https://github.com/enyo/dropzone/issues/418
Ответ 2
В зависимости от вашей ситуации вы можете просто отправить форму:
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
} else {
$("#my_form").submit();
}
Ответ 3
Я попробовал ответ Matija Grcic и получил следующую ошибку:
Uncaught TypeError: Cannot read property 'name' of undefined
И я не хотел изменять исходный код dropzone, поэтому я сделал следующее:
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
} else {
myDropzone.uploadFiles([{name:'nofiles'}]); //send empty
}
Примечание. Я передаю объект внутри массива функции uploadFiles.
Затем я проверяю серверную сторону, если имя!= 'nofiles' загружает файл.
Ответ 4
Первый подход для меня слишком дорог, я бы не хотел погружаться в исходный код и изменять его,
Если вы похожи на меня, используйте это.
function submitMyFormWithData(url)
{
formData = new FormData();
//formData.append('nameOfInputField', $('input[name="nameOfInputField"]').val() );
$.ajax({
url: url,
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
И в вашей dropzone script
$("#submit").on("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
if (myDropzone.getQueuedFiles().length > 0)
{
myDropzone.processQueue();
} else {
submitMyFormWithData(ajaxURL);
}
});
Ответ 5
Я успешно использовал:
submitButton.addEventListener("click", function () {
if(wrapperThis.files.length){
error = `Please select a file`;
} else {
wrapperThis.processQueue();
}
});
Ответ 6
Вы должны проверить, есть ли файлы в очереди. Если очередь пуста, вызовите непосредственно dropzone.uploadFile(). Этот метод требует, чтобы вы передавали файл. Как указано в [caniuse] [1], конструктор файлов не поддерживается в IE/Edge, поэтому просто используйте Blob API, поскольку на нем основан API файлов.
Метод formData.append(), используемый в dropzone.uploadFile(), требует, чтобы вы передавали объект, который реализует интерфейс Blob. Это причина, по которой вы не можете передать обычный объект.
dropzone version 5.2.0 требует опции upload.chunked
if (this.dropzone.getQueuedFiles().length === 0) {
var blob = new Blob();
blob.upload = { 'chunked': this.dropzone.defaultOptions.chunking };
this.dropzone.uploadFile(blob);
} else {
this.dropzone.processQueue();
}