Имеется такой код:
<form action="/admin/addBanner" method="post" enctype="multipart/form-data">
<input class="upload-btn" id="upload-btn" type="file" name="file" multiple>
<button class="d-td-button-action fs-medium ff-SansNarrow" type="submit">Сохранить</button>
</form>
....
//в скрипте имеется массив файлов(изображений) хранящихся в files
var files = e.dataTransfer.files;
Как передать объекты из files в input type file
var $ = jQuery.noConflict();
$(document).ready(function() {
// В dataTransfer помещаются изображения которые перетащили в область div
jQuery.event.props.push('dataTransfer');
// Максимальное количество загружаемых изображений за одни раз
var maxFiles = 1;
// Оповещение по умолчанию
var errMessage = 0;
// Кнопка выбора файлов
var defaultUploadBtn = $('.upload-btn');
// Массив для всех изображений
var dataArray = [];
// Метод при падении файла в зону загрузки
$('.upload-container').on('drop', function(e) {
// Передаем в files все полученные изображения
var files = e.dataTransfer.files;
// Проверяем на максимальное количество файлов
if (files.length <= maxFiles) {
// Передаем массив с файлами в функцию загрузки на предпросмотр
loadInView(files);
} else {
alert('Вы не можете загружать изображения больше '+maxFiles+'!');
files.length = 0; return;
}
});
// При нажатии на кнопку выбора файлов
defaultUploadBtn.on('change', function() {
// Заполняем массив выбранными изображениями
var files = $(this)[0].files;
// Проверяем на максимальное количество файлов
if (files.length <= maxFiles) {
// Передаем массив с файлами в функцию загрузки на предпросмотр
loadInView(files);
// Очищаем инпут файл путем сброса формы
$('.upload-form').each(function(){
this.reset();
});
} else {
alert('Вы не можете загружать изображения больше '+maxFiles+'!');
files.length = 0;
}
});
// Функция загрузки изображений на предросмотр
function loadInView(files) {
// Показываем обасть предпросмотра
$('.uploaded-holder').show();
// Для каждого файла
$.each(files, function(index, file) {
// Несколько оповещений при попытке загрузить не изображение
if (!files[index].type.match('image.*')) {
if(errMessage == 0) {
$('.upload-container span').html('Ошибка!');
++errMessage
}
return false;
}
else {
$('.upload-container span').html("или перетащите");
}
// Проверяем количество загружаемых элементов
if((dataArray.length+files.length) > maxFiles) {
alert('Вы не можете загружать изображения больше '+maxFiles+'!'); return;
}
// Создаем новый экземпляра FileReader
var fileReader = new FileReader();
// Инициируем функцию FileReader
fileReader.onload = (function(file) {
return function(e) {
// Помещаем URI изображения в массив
dataArray.push({name : file.name, value : this.result});
addImage((dataArray.length-1));
};
})(files[index]);
// Производим чтение картинки по URI
fileReader.readAsDataURL(file);
});
return false;
}
// Процедура добавления эскизов на страницу
function addImage(ind) {
// Если индекс отрицательный значит выводим весь массив изображений
if (ind < 0 ) {
start = 0; end = dataArray.length;
} else {
// иначе только определенное изображение
start = ind; end = ind+1; }
// Оповещения о загруженных файлах
if(dataArray.length == 0) {
$('.uploaded-holder').hide();
}
// Цикл для каждого элемента массива
for (i = start; i < end; i++) {
// размещаем загруженные изображения
if($('.dropped-container > .image').length <= maxFiles) {
$('.dropped-container').append('<img class="d-table-img" src="'+dataArray[i].value+'">');
}
}
return false;
}
// next script
var dropZone = $('.upload-container');
$('.upload-btn').focus(function() {
$('label').addClass('focus');
})
.focusout(function() {
$('label').removeClass('focus');
});
dropZone.on('drag dragstart dragend dragover dragenter dragleave drop', function(){
return false;
});
dropZone.on('dragover dragenter', function() {
dropZone.addClass('dragover');
});
dropZone.on('dragleave', function(e) {
let dx = e.pageX - dropZone.offset().left;
let dy = e.pageY - dropZone.offset().top;
if ((dx < 0) || (dx > dropZone.width()) || (dy < 0) || (dy > dropZone.height())) {
dropZone.removeClass('dragover');
}
});
dropZone.on('drop', function(e) {
dropZone.removeClass('dragover');
let files = e.originalEvent.dataTransfer.files;
sendFiles(files);
});
$('.upload-btn').change(function() {
let files = this.files;
sendFiles(files);
});
function sendFiles(files) {
var json;
let Data = new FormData();
Data.append('text', 'fdgd');
$(files).each(function(index, file) {
Data.append('file', file);
});
$.ajax({
url: '/admin/addBanner',
type: 'post',
data: Data,
contentType: false,
processData: false,
success: function(result) {
json = jQuery.parseJSON(result);
if (json.url) {
window.location.href = '/' + json.url;
} else {
alert(json.status + ' - ' + json.message);
}
}
});
}
$('form').submit(function(event) { })
});
.d-table {
display: flex;
flex-flow: column nowrap;
flex: 1 1 auto;
padding: 45px;
}
.d-th {
display: none;
text-transform: uppercase;
}
.d-tr {
display: flex;
flex-flow: row nowrap;
}
.d-td {
display: flex;
flex-flow: row nowrap;
flex-grow: 1;
flex-basis: 0;
padding: 10px;
min-width: 100px;
border-bottom: 1px solid gray;
white-space: normal;
justify-content: center;
align-items: center;
}
.d-td-img {
display: flex;
flex-flow: row nowrap;
flex-grow: 3;
flex-basis: 0;
padding: 10px;
min-width: 100px;
border-bottom: 1px solid gray;
white-space: normal;
justify-content: center;
align-items: center;
}
.d-table-img {
width: 100%;
max-width: 200px;
height: 100px;
}
.upload-container {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
width: 110px;
height: 110px;
outline: 2px dashed #5d5d5d;
outline-offset: -12px;
background-color: rgba(76,175,80,.6);
text-align: center;
}
.upload-container-img {
width: 50px;
height: 50px;
user-select: none;
}
.upload-container-label {
font-weight: bold;
}
.upload-container-label:hover {
cursor: pointer;
text-decoration: underline;
}
.upload-container input[type=file] {
display:none;
}
.upload-container-label input[type=file]:focus + label {
outline: 1px solid #0078d7;
outline: -webkit-focus-ring-color auto 5px;
}
.upload-container.dragover {
background-color: rgba(76,175,80,.2);
outline-offset: -17px;
}
.drop-files {
position:relative;
width: 500px;
height: 140px;
margin: 0 auto;
background: rgba(0,0,0,0.1);
border-radius: 10px;
border: 4px dashed rgba(0,0,0,0.2);
padding-top:80px;
text-align: center;
font-size: 2em;
font-weight: bold;
}
.drop-files p {
clear:none;
padding:0;
margin:0;
}
.uploaded-holder {
display: none;
position:relative;
margin: 0 auto;
}
.dropped-files {
display:block;
margin: 0 auto;
width: 950px;
}
.drop-button {
display: block;
position: absolute;
z-index: 9999;
padding: 5px;
width: 100%;
background: rgba(0,0,0,0.6);
font-size: 1em;
bottom: 0;
text-align: center;
text-decoration: none;
font-weight: 700;
color: #FFF;
}
.dropped-files .image {
position: relative;
height: 200px;
width: 300px;
border: 4px solid #fff;
box-shadow: 0px 0px 10px rgba(0,0,0,0.1);
background: #fff;
float: left;
border-radius: 4px;
margin: 0 7px 7px 0;
overflow: hidden;
}
.dropped-files .delete {
padding: 7px 6px 4px 6px;
border-radius: 100px;
background: rgba(0,0,0,0.6);
box-shadow: none;
font-size: 1em;
margin-left: 8px;
}
.dropped-files .delete:hover {
background: rgba(0,0,0,0.8);
}
ы
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/3.0.0/jquery-migrate.min.js"></script>
<div class="d-table ff-SansNarrow">
<form action="/admin/addBanner" method="post" enctype="multipart/form-data">
<div class="d-tr">
<span class="d-td-img">
<div class="dropped-container">
<!--<a href="#img1">
<img class="d-table-img" src="/public/images/banners/74.jpg">
</a>-->
</div>
</span>
<span class="d-td" style="flex-grow: 2;">
<div>
<div class="upload-container">
<input class="upload-btn" id="upload-btn" type="file" name="file" multiple>
<label class="upload-container-label" for="upload-btn" data-count="1">Выберите файл</label>
<span>или перетащите</span>
</div>
</div>
</span>
<span class="d-td">
<input class="d-th" type="text" name="file2">
<button class="d-td-button-action" type="submit">Сохранить</button>
</span>
</div>
</div>
</form>
</div>
Если в скрипт добавить $('form').submit(function(event) { } то будет открываться файл, а надо что бы выполнялся скрипт. И еще в функции sendFiles(files) я добавляю Data.append('text', 'fdgd'); так как без него не передается, почему не знаю