У меня несколько дропзон (Dynami c, каждый продукт представляет собой продукт, который добавлен в корзину в моем интернет-магазине).
Для каждого загружаемого изображения выполняется вызов ajax, который возвращает информацию о загруженном изображении и отображает ее в шаблоне предварительного просмотра (блок уменьшенных изображений загруженного изображения). Информация, как размеры, DPI и имя файла.
Проблема в том, что информация всегда отображается только в последней зоне сброса, в последнем шаблоне предварительного просмотра.
Например:
When I have two dropzones.
I upload an image of 20DPI in the first one, result: no information is shown in the preview.
I upload an image of 20DPI in the second one, result: the preview is shown with 20 DPI as information which is correct.
I upload two images at the same time in the second dropzone, the first image with 20DPI the second one with 72DPI, result: the first preview is empty and the last preview briefly shows 20DPI before it is overwritten with 72DPI.
Это означает, что информация получена правильно, она просто неправильно размещена в шаблонах предварительного просмотра.
Это мой код дропзоны, он проходит через все .dropzone
классы:
$('.dropzone').each(function(index){
$maxfiles = $(this).attr('maxfiles');
$inputquantity = $(this).find('input').val();
$thisdropzone = $(this);
$(this).dropzone({
paramName: 'postedFile',
addRemoveLinks: true,
dictDefaultMessage: '<i class="fas fa-file-upload uploadicon"></i> <span class="uploadtxt">Upload je bestand(en)</span>',
dictRemoveFile: 'Verwijder',
dictCancelUpload: 'Annuleren',
dictInvalidFileType: 'Dit type bestand is niet toegestaan',
dictCancelUploadConfirmation: 'Weet je zeker dat je het uploaden wilt annuleren?',
dictMaxFilesExceeded: 'Maximale aantal bestanden overschreden',
maxFiles: $maxfiles,
acceptedFiles: '.jpg, .jpeg, .png, .pdf, .tif, .tiff',
thumbnailWidth: '205',
thumbnailHeight: '140',
thumbnailMethod: 'crop',
previewTemplate: $(".hiddendiv").html(),
sending: function (file) {
},
// File contains dropzone file object, response contains ajax response from php file
success: function (file, response) {
var obj = JSON.parse(response);
$($thisdropzone).find('.dz-preview:last .bestandnaam').text('Bestandsnaam: ' + obj[0].filename);
$($thisdropzone).find('.dz-preview:last .resolutie').text('Resolutie: ' + obj[0].dpi + ' DPI');
$($thisdropzone).find('.dz-preview:last .formaat').text('Formaat: ' + obj[0].heightcm + ' x ' + obj[0].widthcm + 'cm');
},
})
});
И это мой html с в этом примере двумя дропзонами (формами):
<table class="table upload-table">
<tbody>
<tr>
<td class="plantmore-product-thumbnail uploadimg" width="100">
<a href=""><img src="assets/images/noimg.jpg" alt=""></a>
</td>
<td class="plantmore-product-name" width="200">
<div class="prodinfocheckout">
<a class="prodname" href="">
Monomeer
</a>
<span id="togglespecscheckout" class="prodspecscheckout noselect">
<i class="fas fa-chevron-down"></i> Specificaties
</span>
<div class="togglespecscheckout">
Hoogte : 20cm
<br>
Breedte : 20cm
<br>
uploaden : 1
<br>
Lijmlaag : Wit
<br>
Laminaat : Anti-slip laminaat
<br>
Afwerking : Contoursnijden
<br>
</div>
</div>
</td>
<td class="plantmore-product-quantity" width="190">
<span class="centervertical">
<button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
<i class="fas fa-info-circle"></i>
</button>
<span class="amount">
Benodigd formaat:<br>
<span class="benodigd">20 x 20cm</span>
</span>
</span>
</td>
<td class="plantmore-product-quantity" width="185">
<span class="centervertical">
<button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
<i class="fas fa-info-circle"></i>
</button>
<span class="amount">Benodigde aantal<br> bestanden: <span class="benodigd">10</span></span>
</span>
</td>
<td class="plantmore-product-quantity">
<span class="centervertical">
<button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
<i class="fas fa-info-circle"></i>
</button>
<span class="amount">Bestanden <br>toegewezen: <span class="benodigd">0 / 10</span></span>
</span>
</td>
<td class="plantmore-product-quantity" valign="top">
<button class="uploadbutton btn yellowbtn dz-clickable">Bestand(en) uploaden</button>
</td>
</tr>
<tr class="newrow">
<td colspan="6">
<form action="upload/uploaden.php" class="dropzone dropzoneform dz-clickable" maxfiles="10" id="dropzone1">
<input type="hidden" value="Monomeer" name="productnaam">
<input type="hidden" value="Twan" name="klantnaam">
<input type="hidden" value="20" name="hoogte">
<input type="hidden" value="20" name="breedte">
<div class="dz-default dz-message"><span><i class="fas fa-file-upload uploadicon"></i> <span class="uploadtxt">Upload je bestand(en)</span></span></div>
</form>
</td>
</tr>
<tr>
<td class="plantmore-product-thumbnail uploadimg" width="100">
<a href=""><img src="assets/images/noimg.jpg" alt=""></a>
</td>
<td class="plantmore-product-name" width="200">
<div class="prodinfocheckout">
<a class="prodname" href="">
Monomeer
</a>
<span id="togglespecscheckout" class="prodspecscheckout noselect">
<i class="fas fa-chevron-down"></i> Specificaties
</span>
<div class="togglespecscheckout">
Hoogte : 90cm
<br>
Breedte : 90cm
<br>
uploaden : 1
<br>
Lijmlaag : Wit
<br>
Laminaat : Anti-slip laminaat
<br>
Afwerking : Contoursnijden
<br>
</div>
</div>
</td>
<td class="plantmore-product-quantity" width="190">
<span class="centervertical">
<button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
<i class="fas fa-info-circle"></i>
</button>
<span class="amount">
Benodigd formaat:<br>
<span class="benodigd">90 x 90cm</span>
</span>
</span>
</td>
<td class="plantmore-product-quantity" width="185">
<span class="centervertical">
<button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
<i class="fas fa-info-circle"></i>
</button>
<span class="amount">Benodigde aantal<br> bestanden: <span class="benodigd">1</span></span>
</span>
</td>
<td class="plantmore-product-quantity">
<span class="centervertical">
<button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
<i class="fas fa-info-circle"></i>
</button>
<span class="amount">Bestanden <br>toegewezen: <span class="benodigd">0 / 1</span></span>
</span>
</td>
<td class="plantmore-product-quantity" valign="top">
<button class="uploadbutton btn yellowbtn dz-clickable">Bestand(en) uploaden</button>
</td>
</tr>
<tr class="newrow">
<td colspan="6">
<form action="upload/uploaden.php" class="dropzone dropzoneform dz-clickable" maxfiles="1" id="dropzone4">
<input type="hidden" value="Monomeer" name="productnaam">
<input type="hidden" value="Twan" name="klantnaam">
<input type="hidden" value="90" name="hoogte">
<input type="hidden" value="90" name="breedte">
<div class="dz-default dz-message"><span><i class="fas fa-file-upload uploadicon"></i> <span class="uploadtxt">Upload je bestand(en)</span></span></div>
</form>
</td>
</tr>
</tbody>
</table>
Что может быть причиной ошибок? Я попытался удалить детали :last
и загрузить только одно изображение в первом и одно во втором. Но первый предварительный просмотр все еще не содержит никакой информации.
Это мой пользовательский элемент предварительного просмотра внутри .hiddendiv
, он находится под дропзонами в моем DOM:
<div class="hiddendiv">
<div class="dz-preview dz-file-preview">
<div class="dz-image"><img data-dz-thumbnail /></div>
<div class="dz-details">
<div class="dz-size"><span data-dz-size></span></div>
<div class="dz-filename"><span data-dz-name></span></div>
</div>
<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
<span class="infoline">
<span class="infospan bestandnaam">Bestandnaam:</span>
<!-- <i class="fas fa-times-circle afgekeurd"></i> -->
</span>
<span class="infoline">
<span class="infospan resolutie">Resolutie:</span>
<!-- <i class="fas fa-check-circle goedgekeurd"></i> -->
</span>
<span class="infoline">
<span class="infospan formaat">Formaat:</span>
<!-- <i class="fas fa-times-circle afgekeurd"></i> -->
</span>
<div class="foutformaat">
<span>Bestand heeft niet het benodigde formaat.</span>
<span class="uploadinfobox">
<button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
<i class="fas fa-info-circle"></i>
</button>
</span>
</div>
<button class="yellowbtn btn vrijgevenbtn" type="button">Bestand vrijgeven</button>
<hr class="uploadline">
<span class="toewijzen">Aantal</span>
<div class="uploadcontent">
<input type="text" class="fileinput">
<button class="plusminupload" id="minupload">−</button>
<button class="plusminupload" id="plusupload">+</button>
</div>
</div>
</div>
Обновлен код из ответа ниже:
$('.dropzone').each(function(index, element){
let $el = $(element);
let $maxfiles = $el.attr('maxfiles');
let $inputquantity = $el.find('input').val();
let $thispreview = $el.find('.hiddendiv');
let $thisdropzone = $el;
// $maxfiles = $(this).attr('maxfiles');
// $inputquantity = $(this).find('input').val();
// $thisdropzone = $(this);
// $thispreview = $(this).find('.hiddendiv');
$(this).dropzone({
// clickable: ".uploadbutton, .dropzoneform",
paramName: 'postedFile',
addRemoveLinks: true,
dictDefaultMessage: '<i class="fas fa-file-upload uploadicon"></i> <span class="uploadtxt">Upload je bestand(en)</span>',
dictRemoveFile: 'Verwijder',
dictCancelUpload: 'Annuleren',
dictInvalidFileType: 'Dit type bestand is niet toegestaan',
dictCancelUploadConfirmation: 'Weet je zeker dat je het uploaden wilt annuleren?',
dictMaxFilesExceeded: 'Maximale aantal bestanden overschreden',
maxFiles: $maxfiles,
acceptedFiles: '.jpg, .jpeg, .png, .pdf, .tif, .tiff',
thumbnailWidth: '205',
thumbnailHeight: '140',
thumbnailMethod: 'crop',
previewTemplate: $thispreview.html(),
processing: function (file) {
},
// File contains dropzone file object, response contains ajax response from php file
success: function (file, response) {
// alert('test');
let file_meta = JSON.parse(response);
let $preview = $thisdropzone.find('.dz-preview:last');
if(file_meta[0].status == 'success'){
}else if(file_meta[0].status == 'error'){
$preview.find('.vrijgevenbtn').show();
$preview.find('.foutformaat').show();
}
$preview.find('.bestandnaam').text('Bestandsnaam: ' + file_meta[0].filename);
$preview.find('.resolutie').text('Resolutie: ' + file_meta[0].dpi + ' DPI');
$preview.find('.formaat').text('Formaat: ' + file_meta[0].heightcm + ' x ' + file_meta[0].widthcm + 'cm');
},
})
});
Вот что происходит, когда я загружаю несколько изображений за один выбор: выбор трех изображений с моего компьютера:
![enter image description here](https://i.stack.imgur.com/gJo0v.png)
Три предварительных просмотра в зоне сброса, причем только последний имеет данные:
![enter image description here](https://i.stack.imgur.com/TE9rv.png)
Каждое изображение возвращает строку json, которая в этом примере:
[{"status":"error","filename":"instablok.jpg","filesize":22822,"tmp_name":"\/tmp\/phpI6ov6y","height":172,"width":565,"heightcm":"6,07","widthcm":"19,93","tifwidth":null,"dpi":"72"}]
[{"status":"error","filename":"fbblok.jpg","filesize":17349,"tmp_name":"\/tmp\/phpBzh40y","height":172,"width":565,"heightcm":"6,07","widthcm":"19,93","tifwidth":null,"dpi":"72"}]
[{"status":"error","filename":"logo-dark.png","filesize":21137,"tmp_name":"\/tmp\/phpCHGGZg","height":154,"width":881,"heightcm":"5,43","widthcm":"31,08","tifwidth":null,"dpi":"72"}]
Все они возвращаются отдельно. Странно то, что все данные добавляются в последний предварительный просмотр и перезаписываются более новым. Таким образом, последний предварительный просмотр сначала содержит данные из первого возвращенного json, затем второго и, наконец, последнего правильного, в то время как первые два остаются пустыми.
Вы можете проверить с этими двумя ссылками:
Сначала добавьте товар в вашу корзину здесь: https://printzelf.nl/new/folie/monomeer Вы Aantal
означает количество, и это будет определять, сколько изображений можно загрузить в зоне сброса, поэтому вам нужно более 1, чтобы иметь возможность видеть ошибка.
Когда вы закончите, нажимая на опции, вы можете добавить его Toevoegen
. Затем go на ссылку на страницу dropzone, которая: https://printzelf.nl/new/bestanden-uploaden