-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-download.html
More file actions
191 lines (165 loc) · 8.53 KB
/
test-download.html
File metadata and controls
191 lines (165 loc) · 8.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Тест скачивания CSV</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 50px auto;
padding: 20px;
}
button {
background: #0066cc;
color: white;
border: none;
padding: 12px 24px;
font-size: 16px;
border-radius: 6px;
cursor: pointer;
margin: 10px;
}
button:hover {
background: #0052a3;
}
#log {
background: #f5f5f5;
border: 1px solid #ddd;
padding: 15px;
border-radius: 6px;
margin-top: 20px;
font-family: monospace;
font-size: 12px;
max-height: 400px;
overflow-y: auto;
}
.success { color: green; }
.error { color: red; }
.info { color: blue; }
</style>
</head>
<body>
<h1>🧪 Тест скачивания CSV шаблона</h1>
<div>
<button onclick="downloadTemplate()">📥 Скачать шаблон (основной метод)</button>
<button onclick="downloadTemplateAlt()">📥 Скачать шаблон (альтернативный)</button>
<button onclick="clearLog()">🗑️ Очистить лог</button>
</div>
<div id="log"></div>
<script>
function log(message, type = 'info') {
const logDiv = document.getElementById('log');
const timestamp = new Date().toLocaleTimeString();
const className = type === 'error' ? 'error' : type === 'success' ? 'success' : 'info';
logDiv.innerHTML += `<div class="${className}">[${timestamp}] ${message}</div>`;
logDiv.scrollTop = logDiv.scrollHeight;
}
function clearLog() {
document.getElementById('log').innerHTML = '';
}
function downloadTemplate() {
try {
log('🚀 Начало скачивания (основной метод)...', 'info');
const templateData = [
['Имя / Ad / Name', 'Должность / Pozisyon / Position', 'Роль / Rol / Role', 'Email', 'Телефон / Telefon / Phone'],
['Иванов Иван Иванович', 'Директор по ОТ и ПБ', 'issuer', 'ivanov@example.com', '+79991234567'],
['Ahmet Yılmaz', 'Операционный директор', 'supervisor', 'ahmet@example.com', '+905551234567'],
['Петров Петр', 'Мастер-производитель', 'foreman', 'petrov@example.com', '+79991234568'],
['Сидоров Сергей', 'Рабочий-монтажник', 'worker', 'sidorov@example.com', '+79991234569'],
['', '', '', '', ''],
['Роли / Roller / Roles:', '', '', '', ''],
['issuer', '- Выдающий наряд / İzin Veren / Permit Issuer', '', '', ''],
['supervisor', '- Ответственный руководитель / Sorumlu Yönetici / Supervisor', '', '', ''],
['foreman', '- Производитель работ / İş Sorumlusu / Foreman', '', '', ''],
['worker', '- Рабочий / İşçi / Worker', '', '', ''],
];
// Определяем разделитель
const isWindowsLikeLocale = navigator.language.includes('ru') ||
navigator.language.includes('tr') ||
navigator.platform.includes('Win');
const delimiter = isWindowsLikeLocale ? ';' : ',';
log(`📊 Платформа: ${navigator.platform}`, 'info');
log(`🌍 Локаль: ${navigator.language}`, 'info');
log(`🔹 Разделитель: "${delimiter}"`, 'info');
// Создаем CSV с UTF-8 BOM
const BOM = '\uFEFF';
const csvContent = templateData.map(row =>
row.map(cell => {
if (cell.includes(delimiter) || cell.includes('"') || cell.includes('\n') || cell.includes('\r')) {
return `"${cell.replace(/"/g, '""')}"`;
}
return cell;
}).join(delimiter)
).join('\r\n');
log(`📄 Размер CSV: ${csvContent.length} символов`, 'info');
// Создаем Blob
const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' });
log(`💾 Размер Blob: ${blob.size} байт`, 'info');
// Создаем ссылку для скачивания
const url = window.URL.createObjectURL(blob);
log(`🔗 Blob URL создан: ${url.substring(0, 50)}...`, 'info');
const link = document.createElement('a');
link.href = url;
link.download = 'personnel_template.csv';
link.style.display = 'none';
document.body.appendChild(link);
log('➕ Ссылка добавлена в DOM', 'info');
setTimeout(() => {
try {
link.click();
log('✅ Клик выполнен! Файл должен скачаться.', 'success');
setTimeout(() => {
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
log('🧹 Очистка выполнена', 'info');
}, 100);
} catch (error) {
log(`❌ Ошибка при клике: ${error.message}`, 'error');
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
}
}, 0);
} catch (error) {
log(`❌ ОШИБКА: ${error.message}`, 'error');
console.error(error);
}
}
function downloadTemplateAlt() {
try {
log('🚀 Начало скачивания (альтернативный метод)...', 'info');
const templateData = [
['Имя', 'Должность', 'Роль', 'Email', 'Телефон'],
['Иванов Иван', 'Директор', 'issuer', 'ivanov@example.com', '+79991234567'],
['Петров Петр', 'Мастер', 'foreman', 'petrov@example.com', '+79991234568'],
];
const delimiter = ';';
const BOM = '\uFEFF';
const csvContent = templateData.map(row => row.join(delimiter)).join('\r\n');
// Альтернативный метод через data URI
const dataUri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(BOM + csvContent);
const link = document.createElement('a');
link.href = dataUri;
link.download = 'personnel_template_alt.csv';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
log('✅ Скачивание через data URI выполнено!', 'success');
} catch (error) {
log(`❌ ОШИБКА: ${error.message}`, 'error');
console.error(error);
}
}
// Автоматический лог при загрузке
window.addEventListener('load', () => {
log('🌐 Страница загружена', 'success');
log(`🖥️ User Agent: ${navigator.userAgent}`, 'info');
log(`📱 Платформа: ${navigator.platform}`, 'info');
log(`🌍 Язык: ${navigator.language}`, 'info');
log('', 'info');
log('👆 Нажмите кнопку для скачивания', 'info');
});
</script>
</body>
</html>