add form upload support

This commit is contained in:
themohooks 2024-07-05 07:59:53 +03:00
parent 429e512eee
commit 89011a09fd
4 changed files with 184 additions and 265 deletions

View file

@ -86,107 +86,7 @@ $(document).ready(function()
});
// Строка добавления нового ТС
$('#vlist').on('mouseenter mouseleave', '#add_new_vehicle', function()
{
var state = parseInt($(this).data('state'));
$(this).toggleClass('s' + state + ' s' + (state+10));
})
.on('click', '#add_new_vehicle', function()
{
new_vehicle_idx++;
var nid = -new_vehicle_idx;
var cid = $('#search_cid').val();
var num = $('#search_num').val();
var gos = $('#search_gos').val();
var type = $('#search_type').val();
var cname = $('#cname').val();
var by_gos = ($(this).attr('bygos') == 1);
var html = '<tbody data-nid="' + nid + '" class="s1">\n';
html += '<tr>\n';
html += '<td style="padding:3px 10px 5px"><input type="hidden" name="nids[]" value="' + nid + '"><input type="hidden" name="cids[]" value="' + cid + '"><span class="num">' + (by_gos ? gos : num) + '</span></td>\n';
html += '<td style="padding:3px 10px 6px">' + $('#search_type option:selected').html() + '</td>\n';
html += '<td style="padding:3px 0 6px 10px; color:#777" class="r">' + _text['UP_ROUTE'] + ':</td>\n';
html += '<td style="padding:3px 7px" class="nw"><input type="text" class="route" name="route[' + nid + ']" style="width:40px; font-weight:bold; text-align:center" maxlength="7" value="">, <input type="text" class="notes" name="notes[' + nid + ']" style="width:170px" maxlength="100" value="" placeholder="' + _text['UP_NOTES'] + '"></td>\n';
html += '<td class="r"><a href="#" class="delLink" style="font-size:16px">&times;</a></td>\n';
html += '</tr>\n';
html += '<tr>\n';
html += '<td style="padding:0 12px 7px" colspan="2"><a href="/city/' + cid + '/" target="_blank">' + cname + '</a></td>\n';
html += '<td style="padding:0 0 7px; color:#777" class="r">' + _text['VIEW'] + ':</td>\n';
html += '<td style="padding:0 7px 7px" colspan="2"><input type="hidden" class="view" name="view[' + nid + ']" value="0"><a href="#" class="view_link dot">' + views[0] + '</a></td>\n';
html += '</tr>\n';
html += '<tr>\n';
html += '<td colspan="2"></td>\n';
html += '<td style="padding:0 0 7px; color:#777" class="r">' + _text['UP_BIND'] + ':</td>\n';
html += '<td style="padding:0 7px 7px" colspan="2"><input type="hidden" name="pri[' + nid + ']" class="pri-value" value="1"><a class="pri-label dot" href="#">' + binds[0].label + '</a></td>\n';
html += '</tr>\n';
html += '<tr>\n';
html += '<td id="new_vehicle_' + new_vehicle_idx + '" style="padding:5px" colspan="6">' + _text['UP_LOADING'] + '</td>\n';
html += '</tr>\n';
html += '</tbody>\n';
var row = $(html);
$('#conn_veh').append(row).show().tablesort('recountRows');
$('.pri-label', row).selector2(binds);
$('.no-links').hide();
cnames[cid] = cname;
var form = $('.new_vehicle_template').clone(true).removeClass('new_vehicle_template').show();
$('select[name="nv_service[]"]', form).change();
$('select[name="nv_state[]"]', form).change();
$('input[name="nv_cid[]"]', form).val(cid);
$('input[name="nv_type[]"]', form).val(type);
$('input[name="nv_num[]"]', form).val(num);
$('input[name="nv_gos[]"]', form).val(gos);
if (by_gos)
$('.tbody_nv_num', form).css('display', '');
else $('.tbody_nv_gos', form).css('display', '');
$.get('/api.php', { action: 'get-depot-list', cid: cid }, function(data)
{
$('.did', form).html(data);
$('.tbody_nv_did', form).css('display', (data != '') ? '' : 'none');
$('#new_vehicle_' + new_vehicle_idx).empty().append(form);
$('input[name="nv_mid[]"]', form).attr('id', 'mid_' + new_vehicle_idx);
$('input[name="nv_chid[]"]', form).attr('id', 'chid_' + new_vehicle_idx);
var nv_type = $('input[name="nv_type[]"]', form);
$('.mname', form).autocompleteSelector('mid_' + new_vehicle_idx, '/api.php?action=get-models', {
minLength: 1,
paramsCallback: function(params) { params.type = nv_type.val(); },
selectCallback: function(item) { form.closest('tbody').data('twoside', item.twoside); }
});
$('.chname', form).autocompleteSelector('chid_' + new_vehicle_idx, '/api.php?action=get-chassis', {
minLength: 1,
paramsCallback: function(params) { params.type = nv_type.val(); }
});
$('.did', form).select2();
showDefaultCity();
})
.fail(function(jx) { alert(jx.responseText); });
modify();
});
@ -409,110 +309,6 @@ function showDefaultCity()
function checkForm()
{
var i, err = '';
function addError(txt) { err += '<li class="sm">' + txt + '.<br>&nbsp;'; }
var image = $('#image');
if (!pid && image.val() == '')
{
$('#step1')[0].scrollIntoView();
image.focus();
alert(_text['UP_NOFILE'] + '.');
return false;
}
// Проверяем наличие привязок вообще
if ($('#links input').length == 0)
{
$('#step2')[0].scrollIntoView();
alert(_text['UP_NOLINKS'] + '.');
return false;
}
if ($('#conn_veh .pri-value[value="1"]').length == 0 &&
$('#conn_veh .pri-value[value="2"]').length == 0 &&
$('#conn_gid tr').length == 0)
{
$('#step2')[0].scrollIntoView();
alert(_text['UP_NO_PRI']);
return false;
}
// Проверим, указаны ли ракурсы
if ($('.view[value="0"]').length > 0)
{
$('#step2')[0].scrollIntoView();
alert(_text['UP_NOVIEW']);
return false;
}
// Проверим корректность привязки творческой фотографии
if ($('#creative').val() == 1 && ($('#conn_veh input[name="nids[]"]').length || $('#conn_gid input[name="gids[]"]').length > 1))
{
$('#step2')[0].scrollIntoView();
alert(_text['UP_CREATIVE']);
return false;
}
// Проверяем наличие даты
if ($('#year').val() == 0 && !confirm(_text['UP_NODATE'] + '.'))
{
$('#step1')[0].scrollIntoView();
return false;
}
// Проверяем разрешение на публикацию
if ($('#naa_hint').is(':visible') && $('#naa_allow').val().trim() == '')
{
alert(_text['UP_NAA_ALLOW_NO']);
$('#step1')[3].scrollIntoView();
return false;
}
// Уточняем, правильно ли, что выбрано "города нет в списке"
var cid = $('#main-cid').val();
if (pid == 0 && cid == 0 && !confirm(_text['UP_NOCITY'])) return false;
// Уточняем, если город не соответствует привязкам
if (cid != 0 && cnames[cid] == undefined && !confirm(_text['UP_OTHERCITY'])) return false;
// Проверяем наличие МС
if ($('.view[value="9"], .view[value="10"], .view[value="11"], .view[value="12"]').length == 0 && $('#place').val().trim() == '' && !confirm(_text['UP_NOPLACE'] + '.'))
{
$('#step3')[0].scrollIntoView();
return false;
}
// Проверяем правильность указания координат
if (!$('#nomap').prop('checked'))
{
if ($('#lat').val() == 0.0 || $('#lng').val() == 0.0)
{
$('#step4')[0].scrollIntoView();
alert(_text['UP_NOCOORDS']);
return false;
}
if ($('#directions input:checked').length == 0)
{
$('#step4')[0].scrollIntoView();
alert(_text['UP_NODIR']);
return false;
}
}
return true;
}

View file

@ -18,7 +18,7 @@ function roundEx(n)
function cannotUpload(input, e)
{
alert(e + '.');
console.log(e);
$(input).val('');
$('#filename, #preview').html('');
}
@ -44,61 +44,7 @@ function checkImageForUpload(input, checksize, successCallback)
var img = new Image();
img.onload = function()
{
var warn = '', need_resize = false;
if (checksize)
{
try
{
if (UPLOAD_MIN_PX &&
(
(img.width >= img.height && img.width < UPLOAD_MIN_PX) ||
(img.width < img.height && img.height < UPLOAD_MIN_PX)
)
) throw formatUploadError(_text['UP_TOOSMALL'], img.width > img.height ? img.width : img.height, UPLOAD_MIN_PX);
if (((ext == 'jpg' || ext == 'webp') && UPLOAD_JPG_MAX_PX && img.width + img.height > UPLOAD_JPG_MAX_PX) ||
((ext != 'jpg' && ext != 'webp') && UPLOAD_PNG_MAX_PX && img.width > UPLOAD_PNG_MAX_PX && img.height > UPLOAD_PNG_MAX_PX))
{
// Если нужно уменьшить - уменьшаем
if (UPLOAD_STD_PX && (ext == 'jpg' || ext == 'webp'))
{
need_resize = true;
warn = formatUploadError(_text['UP_NEEDRESIZE'], UPLOAD_JPG_MAX_PX, UPLOAD_STD_PX);
}
else
if (!can_upload_oversized)
{
if (ext == 'jpg' || ext == 'webp')
throw formatUploadError(_text['UP_OVERSIZE_JPG'], img.width + img.height, UPLOAD_JPG_MAX_PX);
else throw formatUploadError(_text['UP_OVERSIZE_PNG'], img.width > img.height ? img.width : img.height, UPLOAD_PNG_MAX_PX);
}
}
if (!need_resize)
{
var max_size;
if ((ext == 'jpg' || ext == 'webp') && !can_upload_oversized)
max_size = maxsize;
else max_size = UPLOAD_MAX_SIZE * 1024;
if (size > max_size)
{
if (ext == 'jpg' || ext == 'webp')
throw formatUploadError(_text['UP_LARGEFILE_JPG'], Math.ceil(size), max_size);
else throw formatUploadError(_text['UP_LARGEFILE_PNG'], roundEx(size / 1024), UPLOAD_MAX_SIZE);
}
}
}
catch (e)
{
cannotUpload(input, e);
return;
}
}
$('#preview').html((warn ? '<div class="label-orange" style="display:inline-block; padding:3px 7px; margin-bottom:10px">' + warn + '.</div><br />' : '') + '<a href="' + imageUrl + '" target="_blank"><img src="' + imageUrl + '" class="f" /></a><br /><br />');
if (successCallback) successCallback(input);
};

View file

@ -30,7 +30,19 @@
display: block;
}
@media screen and (max-width: 768px) {
:root {
--bckgr: -1500px 0;
--bckgr2: 1500px 0;
}
}
@media screen and (min-width: 768px) {
:root {
--bckgr: -3500px 0;
--bckgr2: 3500px 0;
}
}
@-webkit-keyframes bg-move {
0% { background-position: var(--bckgr); }
100% { background-position: var(--bckgr2); }
@ -41,14 +53,57 @@
}
.progress-bard {
background-color: #3862eb;
background-color: var(--theme-bg-color);
width: 0%;
display: block;
height: inherit;
transition: width 0.6s ease;
background-image: linear-gradient(270deg, rgba(100, 181, 239, 0) 48.44%, #64b5ef 75.52%, rgba(100, 181, 239, 0) 100%);
background-image: linear-gradient(270deg, rgba(100, 181, 239, 0) 48.44%, var(--theme-bg-hover-color) 75.52%, rgba(100, 181, 239, 0) 100%);
background-repeat: no-repeat;
animation: bg-move linear 2s infinite;
}
</style>
</style>
<script>
notie.setOptions({
transitionCurve: 'cubic-bezier(0.2, 0, 0.2, 1)'
});
var Notify = {
noty: function(status, text) {
if (status == 'danger') status = 'error';
return notie.alert({ type: status, text: text })
},
}
function scrollProgressBarWidth(number) {
var getMax = function() {
return $(document).height() - $(window).height();
};
var progressBar = $(".progress-bard"),
max = getMax(),
value,
width;
var setWidth = function() {
progressBar.css({
width: number + '%'
});
};
setWidth();
}
function escapeHtml(text) {
var map = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#039;'
};
return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
</script>

View file

@ -645,7 +645,7 @@ $user = new User(Auth::userid());
<tr>
<td></td>
<td style="padding:20px 2px 12px">
<a id="submitbtn" href="#" class="progress-button" data-loading="Идёт загрузка..." data-finished="Обработка...">Отправить фотографию</a> &nbsp; &nbsp;&nbsp;
<button id="submitbtn" href="#" class="progress-button" data-loading="Идёт загрузка..." data-finished="Обработка..." type="submit">Отправить фотографию</button> &nbsp; &nbsp;&nbsp;
<span id="statusbox" class="narrow" style="font-size:20px; font-weight:bold; position:relative; top:-12px"></span>
<div id="errorsbox" style="display:none; color:red; margin-top:15px; font-weight:bold;"></div>
</td>
@ -662,7 +662,129 @@ $user = new User(Auth::userid());
</tr>
</table>
<script>
$('#mform').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
var continuepost = 0;
$.ajax({
type: "POST",
url: '/api/posts/create',
data: formData,
xhr: function() {
// Добавляем спиннер и блокируем кнопку во время загрузки
//$("#r").html('<button type="submit" id="register" name="loginaccount" class="btn btn-block btn-primary py-2 ripple-handler mt-1 mb-3" disabled><div class="plus-button-reflection"></div>Опубликовать</button>');
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = parseInt(((evt.loaded / evt.total) * 100));
console.log(evt.total);
// Обновляем прогресс загрузки
scrollProgressBarWidth(percentComplete);
}
}, false);
return xhr;
},
success: function(response) {
try {
var jsonData = JSON.parse(response);
} catch (err) {
//$("#r").html('<button id="uploadbtn" style="margin-right: 15px; background: none; border: none; color: aliceblue; " type="submit" name="createpost" class="mb-3 mt-3"><i style="position:relative; font-size: 25px; margin-right: 10px; color: aliceblue; top: 4px;" class="ti ti-message-share uploadbtn"></i>Опубликовать</button>');
$("#prgtd").html('');
$("#prgrsg").html('');
//$("#prgrsg").html('<div id="prgrs" class="progress-bar progress-bar-striped progress-bar-animated bg-danger" role="progressbar" aria-valuenow="0" aria-valuemin="100" aria-valuemax="100" style="width: 100%">100%</div>');
Notify.noty('danger', escapeHtml(err.message));
$("#r").html('<button type="submit" id="register" name="loginaccount" class="btn btn-block btn-primary py-2 ripple-handler mt-1 mb-3">Опубликовать<span class="ripple-mask"><span class="ripple" style=""></span></span></button>');
scrollProgressBarWidth(0);
}
if (jsonData.errorcode == "1") {
$("#r").html('<button type="submit" id="register" name="loginaccount" class="btn btn-block btn-primary py-2 ripple-handler mt-1 mb-3">Опубликовать<span class="ripple-mask"><span class="ripple" style=""></span></span></button>');
//$("#r").html('<button id="uploadbtn" style="margin-right: 15px; background: none; border: none; color: aliceblue; " type="submit" name="createpost" class="mb-3 mt-3"><i style="position:relative; font-size: 25px; margin-right: 10px; color: aliceblue; top: 4px;" class="ti ti-message-share uploadbtn"></i>Опубликовать</button>');
$("#prgtd").html('');
$("#prgrsg").html('');
//$("#prgrsg").html('<div id="prgrs" class="progress-bar progress-bar-striped progress-bar-animated bg-danger" role="progressbar" aria-valuenow="0" aria-valuemin="100" aria-valuemax="100" style="width: 100%">100%</div>');
Notify.noty('danger', 'В посте нет контента!');
scrollProgressBarWidth(0);
} else if (jsonData.errorcode == "101") {
$("#r").html('<button type="submit" id="register" name="loginaccount" class="btn btn-block btn-primary py-2 ripple-handler mt-1 mb-3">Опубликовать<span class="ripple-mask"><span class="ripple" style=""></span></span></button>');
//$("#r").html('<button id="uploadbtn" style="margin-right: 15px; background: none; border: none; color: aliceblue; " type="submit" name="createpost" class="mb-3 mt-3"><i style="position:relative; font-size: 25px; margin-right: 10px; color: aliceblue; top: 4px;" class="ti ti-message-share uploadbtn"></i>Опубликовать</button>');
$("#prgtd").html('');
$("#prgrsg").html('');
//$("#prgrsg").html('<div id="prgrs" class="progress-bar progress-bar-striped progress-bar-animated bg-danger" role="progressbar" aria-valuenow="0" aria-valuemin="100" aria-valuemax="100" style="width: 100%">100%</div>');
Notify.noty('danger', 'В посте больше 10 медиафайлов');
scrollProgressBarWidth(0);
}
else if (jsonData.errorcode == "0") {
Notify.noty('success', 'Успешная публикация!');
$("#r").html('<button type="submit" id="register" name="loginaccount" class="btn btn-block btn-primary py-2 ripple-handler mt-1 mb-3" disabled>Опубликовать<span class="ripple-mask"><span class="ripple" style=""></span></span></button>');
//$("#r").html('<button id="uploadbtn" style="margin-right: 15px; background: none; border: none; color: aliceblue; " type="submit" name="createpost" class="mb-3 mt-3"><i style="position:relative; font-size: 25px; margin-right: 10px; color: aliceblue; top: 4px;" class="ti ti-message-share uploadbtn"></i>Опубликовать</button>');
$("#prgtd").html('');
$("#prgrsg").html('');
/*let positionData = {
id: jsonData.id,
user_id: jsonData.user_id,
text: jsonData.text,
user_flname: jsonData.user_flname,
username: jsonData.username,
user_photo: jsonData.user_photo
};
ws.send(JSON.stringify(positionData));*/
setTimeout(function() {
window.location.replace("/feed");
scrollProgressBarWidth(0);
}, 1000);
} else if (jsonData.errorcode == "LIMITEXCEEDED") {
$("#r").html('<button type="submit" id="register" name="loginaccount" class="btn btn-block btn-primary py-2 ripple-handler mt-1 mb-3">Опубликовать<span class="ripple-mask"><span class="ripple" style=""></span></span></button>');
$("#prgtd").html('');
$("#prgrsg").html('');
//$("#prgrsg").html('<div id="prgrs" class="progress-bar progress-bar-striped progress-bar-animated bg-danger" role="progressbar" aria-valuenow="0" aria-valuemin="100" aria-valuemax="100" style="width: 100%">100%</div>');
//alert('За последнюю минуту вы отправили слишком много запросов. Повторите попытку позже.');
createModal('NONE', 'NONE', 'NONE', 'LIMITEXCEEDED', 'limit');
scrollProgressBarWidth(0);
} else {
$("#r").html('<button type="submit" id="register" name="loginaccount" class="btn btn-block btn-primary py-2 ripple-handler mt-1 mb-3">Опубликовать<span class="ripple-mask"><span class="ripple" style=""></span></span></button>');
$("#prgtd").html('');
$("#prgrsg").html('');
//$("#prgrsg").html('<div id="prgrs" class="progress-bar progress-bar-striped progress-bar-animated bg-danger" role="progressbar" aria-valuenow="0" aria-valuemin="100" aria-valuemax="100" style="width: 100%">100%</div>');
Notify.noty('danger', 'Неизвестная ошибка');
scrollProgressBarWidth(0);
}
},
error: function(xhr, status, error) {
$("#r").html('<button type="submit" id="register" name="loginaccount" class="btn btn-block btn-primary py-2 ripple-handler mt-1 mb-3">Опубликовать<span class="ripple-mask"><span class="ripple" style=""></span></span></button>');
$("#prgtd").html('');
$("#prgrsg").html('');
//$("#prgrsg").html('<div id="prgrs" class="progress-bar progress-bar-striped progress-bar-animated bg-danger" role="progressbar" aria-valuenow="0" aria-valuemin="100" aria-valuemax="100" style="width: 100%">100%</div>');
Notify.noty('danger', 'Не удалось опубликовать пост');
scrollProgressBarWidth(0);
},
cache: false,
contentType: false,
processData: false
});
});
</script>
</body>
</html>