index.html 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. {% extends "base.html" %}
  2. {% block title %}附件上传测试{% endblock %}
  3. {% block extra_styles %}
  4. <style>
  5. .attachment-upload-grid {
  6. display: flex;
  7. flex-wrap: wrap;
  8. gap: 10px;
  9. margin-bottom: 20px;
  10. }
  11. .attachment-upload-grid .btn {
  12. flex: 1 1 auto;
  13. min-width: 140px;
  14. }
  15. .attachment-preview-wrap {
  16. background: #f8f9fa;
  17. border: 1px solid #eee;
  18. border-radius: 10px;
  19. padding: 20px;
  20. min-height: 120px;
  21. }
  22. .attachment-preview-wrap.empty {
  23. color: #888;
  24. display: flex;
  25. align-items: center;
  26. justify-content: center;
  27. }
  28. .attachment-preview-wrap img,
  29. .attachment-preview-wrap video {
  30. max-width: 100%;
  31. max-height: 360px;
  32. border-radius: 8px;
  33. display: block;
  34. }
  35. .attachment-file-meta {
  36. margin-top: 12px;
  37. word-break: break-all;
  38. font-size: 0.9em;
  39. color: #555;
  40. }
  41. .attachment-actions {
  42. display: flex;
  43. flex-wrap: wrap;
  44. gap: 10px;
  45. margin-top: 16px;
  46. }
  47. .attachment-url-box {
  48. font-size: 0.85em;
  49. color: #667eea;
  50. word-break: break-all;
  51. margin-top: 8px;
  52. }
  53. .attachment-ua-footer {
  54. margin-top: 28px;
  55. padding-top: 20px;
  56. border-top: 1px solid #e8e8e8;
  57. }
  58. .attachment-ua-label {
  59. font-size: 0.85em;
  60. color: #888;
  61. margin-bottom: 8px;
  62. }
  63. .attachment-ua-text {
  64. margin: 0;
  65. padding: 12px 14px;
  66. background: #f4f6f8;
  67. border-radius: 8px;
  68. font-size: 0.75em;
  69. line-height: 1.45;
  70. color: #444;
  71. white-space: pre-wrap;
  72. word-break: break-all;
  73. font-family: ui-monospace, Consolas, monospace;
  74. max-height: 200px;
  75. overflow-y: auto;
  76. }
  77. .attachment-fault-modal {
  78. display: none;
  79. position: fixed;
  80. inset: 0;
  81. z-index: 5000;
  82. align-items: center;
  83. justify-content: center;
  84. padding: 16px;
  85. box-sizing: border-box;
  86. }
  87. .attachment-fault-modal.is-open {
  88. display: flex;
  89. }
  90. .attachment-fault-backdrop {
  91. position: absolute;
  92. inset: 0;
  93. background: rgba(0,0,0,0.45);
  94. }
  95. .attachment-fault-dialog {
  96. position: relative;
  97. background: #fff;
  98. border-radius: 12px;
  99. max-width: 520px;
  100. width: 100%;
  101. max-height: 85vh;
  102. display: flex;
  103. flex-direction: column;
  104. box-shadow: 0 8px 32px rgba(0,0,0,0.2);
  105. }
  106. .attachment-fault-dialog h3 {
  107. margin: 0;
  108. padding: 16px 18px 8px;
  109. font-size: 1.1em;
  110. color: #c62828;
  111. }
  112. .attachment-fault-body {
  113. margin: 0 18px 12px;
  114. padding: 12px;
  115. background: #fff5f5;
  116. border: 1px solid #ffcdd2;
  117. border-radius: 8px;
  118. font-size: 0.8em;
  119. line-height: 1.45;
  120. color: #333;
  121. white-space: pre-wrap;
  122. word-break: break-word;
  123. font-family: ui-monospace, Consolas, monospace;
  124. overflow-y: auto;
  125. max-height: min(50vh, 320px);
  126. }
  127. .attachment-fault-actions {
  128. padding: 0 18px 16px;
  129. display: flex;
  130. gap: 10px;
  131. flex-wrap: wrap;
  132. justify-content: flex-end;
  133. }
  134. .attachment-log-panel {
  135. margin-top: 24px;
  136. padding-top: 20px;
  137. border-top: 1px solid #e8e8e8;
  138. }
  139. .attachment-log-panel.collapsed .attachment-log-body {
  140. display: none;
  141. }
  142. .attachment-log-toolbar {
  143. display: flex;
  144. flex-wrap: wrap;
  145. align-items: center;
  146. gap: 10px;
  147. margin-bottom: 10px;
  148. }
  149. .attachment-log-toolbar .attachment-ua-label {
  150. margin-bottom: 0;
  151. flex: 1 1 auto;
  152. }
  153. .attachment-log-body {
  154. margin: 0;
  155. padding: 12px 14px;
  156. background: #1e1e1e;
  157. color: #d4d4d4;
  158. border-radius: 8px;
  159. font-size: 0.7em;
  160. line-height: 1.4;
  161. white-space: pre-wrap;
  162. word-break: break-word;
  163. font-family: ui-monospace, Consolas, monospace;
  164. max-height: 240px;
  165. overflow-y: auto;
  166. -webkit-overflow-scrolling: touch;
  167. }
  168. </style>
  169. {% endblock %}
  170. {% block content %}
  171. <div class="module-header">
  172. <h2>📎 附件上传测试</h2>
  173. </div>
  174. <div class="sub-section">
  175. <h2 style="font-size: 1.1em; margin-bottom: 16px;">选择来源</h2>
  176. <p style="color: #666; margin-bottom: 12px; font-size: 0.95em;">每次仅保留一个附件;新上传会替换当前附件。</p>
  177. <div class="attachment-upload-grid">
  178. <button type="button" class="btn btn-primary" id="btnCameraPhoto">拍照</button>
  179. <button type="button" class="btn btn-primary" id="btnCameraVideo">拍视频</button>
  180. <button type="button" class="btn btn-info" id="btnGalleryImage">相册图片</button>
  181. <button type="button" class="btn btn-info" id="btnGalleryVideo">相册视频</button>
  182. <button type="button" class="btn btn-warning" id="btnAnyFile">选择文件</button>
  183. </div>
  184. <p id="uniappHint" style="display:none;color:#666;font-size:0.9em;margin-bottom:12px;">当前为 UniApp WebView,已使用原生拍照/录像/相册与上传通道。</p>
  185. <input type="file" id="inpCameraPhoto" accept="image/*" capture="environment" style="display:none" />
  186. <input type="file" id="inpCameraVideo" accept="video/*" capture="environment" style="display:none" />
  187. <input type="file" id="inpGalleryImage" accept="image/*" style="display:none" />
  188. <input type="file" id="inpGalleryVideo" accept="video/*" style="display:none" />
  189. <input type="file" id="inpAnyFile" style="display:none" />
  190. <h2 style="font-size: 1.1em; margin: 24px 0 12px;">当前附件</h2>
  191. <div id="previewWrap" class="attachment-preview-wrap empty">暂无附件,请使用上方按钮上传</div>
  192. <div id="previewActions" class="attachment-actions" style="display: none;">
  193. <button type="button" class="btn btn-primary" id="btnShare">分享链接</button>
  194. <button type="button" class="btn btn-secondary" id="btnDelete">删除</button>
  195. </div>
  196. <div id="urlBox" class="attachment-url-box" style="display: none;"></div>
  197. <div class="attachment-ua-footer" id="uaFooter" aria-label="浏览器标识">
  198. <div class="attachment-ua-label">浏览器 User-Agent</div>
  199. <pre id="userAgentText" class="attachment-ua-text"></pre>
  200. </div>
  201. <div class="attachment-log-panel" id="screenLogPanel" aria-label="运行日志">
  202. <div class="attachment-log-toolbar">
  203. <span class="attachment-ua-label">运行日志(手机端无开发者工具时可在此查看)</span>
  204. <button type="button" class="btn btn-info" id="btnLogToggle" style="padding:8px 14px;font-size:0.85em;">收起</button>
  205. <button type="button" class="btn btn-warning" id="btnLogClear" style="padding:8px 14px;font-size:0.85em;">清空</button>
  206. <button type="button" class="btn btn-primary" id="btnLogCopy" style="padding:8px 14px;font-size:0.85em;">复制全部</button>
  207. </div>
  208. <pre id="screenLog" class="attachment-log-body" role="log"></pre>
  209. </div>
  210. </div>
  211. <div id="faultModal" class="attachment-fault-modal" role="dialog" aria-modal="true" aria-labelledby="faultModalTitle" aria-hidden="true">
  212. <div class="attachment-fault-backdrop" id="faultModalBackdrop"></div>
  213. <div class="attachment-fault-dialog">
  214. <h3 id="faultModalTitle">故障信息</h3>
  215. <pre id="faultModalBody" class="attachment-fault-body"></pre>
  216. <div class="attachment-fault-actions">
  217. <button type="button" class="btn btn-info" id="faultModalCopy">复制详情</button>
  218. <button type="button" class="btn btn-primary" id="faultModalClose">确定</button>
  219. </div>
  220. </div>
  221. </div>
  222. {% endblock %}
  223. {% block scripts %}
  224. <script>
  225. (function () {
  226. 'use strict';
  227. var MAX_LINES = 200;
  228. var buffer = [];
  229. function fmtArg(a) {
  230. if (a instanceof Error) {
  231. return a.message + (a.stack ? '\n' + a.stack : '');
  232. }
  233. if (typeof a === 'object' && a !== null) {
  234. try {
  235. return JSON.stringify(a);
  236. } catch (e) {
  237. return String(a);
  238. }
  239. }
  240. return String(a);
  241. }
  242. function flushScreenLog() {
  243. var el = document.getElementById('screenLog');
  244. if (!el) return;
  245. el.textContent = buffer.join('\n');
  246. el.scrollTop = el.scrollHeight;
  247. }
  248. function appendScreenLog(level, args) {
  249. var t = new Date().toISOString().slice(11, 23);
  250. var msg = [].slice.call(args).map(fmtArg).join(' ');
  251. var line = '[' + t + '] ' + level + ' ' + msg;
  252. buffer.push(line);
  253. if (buffer.length > MAX_LINES) {
  254. buffer.shift();
  255. }
  256. flushScreenLog();
  257. }
  258. function patchConsole() {
  259. if (typeof console === 'undefined') return;
  260. ['log', 'warn', 'error', 'info', 'debug'].forEach(function (name) {
  261. var orig = console[name];
  262. if (typeof orig !== 'function') return;
  263. console[name] = function () {
  264. try {
  265. orig.apply(console, arguments);
  266. } catch (e) { /* ignore */ }
  267. appendScreenLog(name.toUpperCase(), arguments);
  268. };
  269. });
  270. }
  271. window.__attachmentLogAppend = function (level, str) {
  272. appendScreenLog(level || 'LOG', [str]);
  273. };
  274. window.__attachmentLogClear = function () {
  275. buffer = [];
  276. flushScreenLog();
  277. };
  278. window.__attachmentLogGetText = function () {
  279. return buffer.join('\n');
  280. };
  281. patchConsole();
  282. window.addEventListener('error', function (ev) {
  283. appendScreenLog('WINDOW', [
  284. (ev.message || '') + ' @' + (ev.filename || '') + ':' + (ev.lineno || 0) + ':' + (ev.colno || 0)
  285. ]);
  286. });
  287. window.addEventListener('unhandledrejection', function (ev) {
  288. var r = ev.reason;
  289. appendScreenLog('REJECT', [r instanceof Error ? r : String(r)]);
  290. });
  291. })();
  292. </script>
  293. <script src="{{ url_for('main.serve_templates_js', filename='im-sdk.js') }}"></script>
  294. <script>
  295. (function () {
  296. let currentUrl = '';
  297. let currentFilename = '';
  298. const previewWrap = document.getElementById('previewWrap');
  299. const previewActions = document.getElementById('previewActions');
  300. const urlBox = document.getElementById('urlBox');
  301. const uniappHint = document.getElementById('uniappHint');
  302. const userAgentText = document.getElementById('userAgentText');
  303. if (userAgentText) {
  304. userAgentText.textContent = navigator.userAgent || '(不可用)';
  305. }
  306. var faultModal = document.getElementById('faultModal');
  307. var faultModalBody = document.getElementById('faultModalBody');
  308. var faultModalTitle = document.getElementById('faultModalTitle');
  309. var faultModalBackdrop = document.getElementById('faultModalBackdrop');
  310. var faultModalClose = document.getElementById('faultModalClose');
  311. var faultModalCopy = document.getElementById('faultModalCopy');
  312. var lastFaultText = '';
  313. function formatErrorDetail(err) {
  314. if (err == null) return '(无详情)';
  315. if (err instanceof Error) {
  316. return err.name + ': ' + err.message + (err.stack ? '\n\n' + err.stack : '');
  317. }
  318. if (typeof err === 'string') return err;
  319. try {
  320. return JSON.stringify(err, null, 2);
  321. } catch (e) {
  322. return String(err);
  323. }
  324. }
  325. function showFaultModal(title, detail) {
  326. var text = formatErrorDetail(detail);
  327. lastFaultText = (title ? title + '\n\n' : '') + text;
  328. if (faultModalTitle) faultModalTitle.textContent = title || '故障信息';
  329. if (faultModalBody) faultModalBody.textContent = lastFaultText;
  330. if (faultModal) {
  331. faultModal.classList.add('is-open');
  332. faultModal.setAttribute('aria-hidden', 'false');
  333. }
  334. console.error('[attachment-test]', title || 'fault', detail);
  335. }
  336. function hideFaultModal() {
  337. if (faultModal) {
  338. faultModal.classList.remove('is-open');
  339. faultModal.setAttribute('aria-hidden', 'true');
  340. }
  341. }
  342. if (faultModalClose) faultModalClose.addEventListener('click', hideFaultModal);
  343. if (faultModalBackdrop) faultModalBackdrop.addEventListener('click', hideFaultModal);
  344. if (faultModalCopy) {
  345. faultModalCopy.addEventListener('click', function () {
  346. if (!lastFaultText) return;
  347. if (navigator.clipboard && navigator.clipboard.writeText) {
  348. navigator.clipboard.writeText(lastFaultText).then(function () {
  349. showMessage('故障详情已复制到剪贴板');
  350. }).catch(function (e) {
  351. showFaultModal('复制失败', e);
  352. });
  353. } else {
  354. showFaultModal('无法复制', '当前环境不支持 clipboard API');
  355. }
  356. });
  357. }
  358. document.addEventListener('keydown', function (e) {
  359. if (e.key === 'Escape' && faultModal && faultModal.classList.contains('is-open')) {
  360. hideFaultModal();
  361. }
  362. });
  363. var screenLogPanel = document.getElementById('screenLogPanel');
  364. var btnLogToggle = document.getElementById('btnLogToggle');
  365. var btnLogClear = document.getElementById('btnLogClear');
  366. var btnLogCopy = document.getElementById('btnLogCopy');
  367. if (btnLogToggle && screenLogPanel) {
  368. btnLogToggle.addEventListener('click', function () {
  369. var collapsed = screenLogPanel.classList.toggle('collapsed');
  370. btnLogToggle.textContent = collapsed ? '展开' : '收起';
  371. });
  372. }
  373. if (btnLogClear && window.__attachmentLogClear) {
  374. btnLogClear.addEventListener('click', function () {
  375. window.__attachmentLogClear();
  376. if (window.__attachmentLogAppend) {
  377. window.__attachmentLogAppend('LOG', '日志已清空');
  378. }
  379. });
  380. }
  381. if (btnLogCopy) {
  382. btnLogCopy.addEventListener('click', function () {
  383. var text = window.__attachmentLogGetText ? window.__attachmentLogGetText() : '';
  384. if (!text) {
  385. showMessage('暂无日志', 'error');
  386. return;
  387. }
  388. if (navigator.clipboard && navigator.clipboard.writeText) {
  389. navigator.clipboard.writeText(text).then(function () {
  390. showMessage('日志已复制');
  391. }).catch(function (e) {
  392. showFaultModal('复制日志失败', e);
  393. });
  394. } else {
  395. showFaultModal('无法复制', '当前环境不支持 clipboard');
  396. }
  397. });
  398. }
  399. if (window.__attachmentLogAppend) {
  400. window.__attachmentLogAppend('LOG', '运行日志已启用(含 im-sdk 与页面内 console)');
  401. }
  402. function useUniNative() {
  403. return window.imSDK && typeof imSDK.isUniAppIm === 'function' && imSDK.isUniAppIm();
  404. }
  405. function refreshUniHint() {
  406. if (uniappHint && useUniNative()) uniappHint.style.display = 'block';
  407. }
  408. refreshUniHint();
  409. setTimeout(refreshUniHint, 400);
  410. function isImageName(name) {
  411. return /\.(png|jpe?g|gif|bmp|webp|heic|heif)$/i.test(name || '');
  412. }
  413. function isVideoName(name) {
  414. return /\.(mp4|mov|webm|mkv|avi)$/i.test(name || '');
  415. }
  416. function clearInputs() {
  417. ['inpCameraPhoto', 'inpCameraVideo', 'inpGalleryImage', 'inpGalleryVideo', 'inpAnyFile'].forEach(function (id) {
  418. const el = document.getElementById(id);
  419. if (el) el.value = '';
  420. });
  421. }
  422. function parseNativeUploadResponse(res) {
  423. if (res == null) return null;
  424. if (typeof res === 'string') {
  425. try { return JSON.parse(res); } catch (e) { return null; }
  426. }
  427. if (typeof res.data === 'string') {
  428. try { return JSON.parse(res.data); } catch (e) { return null; }
  429. }
  430. if (res.data && typeof res.data === 'object') return res.data;
  431. return res;
  432. }
  433. function nativeTempPath(res) {
  434. if (!res) return '';
  435. if (res.tempFilePaths && res.tempFilePaths.length) return res.tempFilePaths[0];
  436. if (res.tempFilePath) return res.tempFilePath;
  437. if (res.apFilePath) return res.apFilePath;
  438. return '';
  439. }
  440. /** 选择图片/视频成功回调:处理 im-sdk 超时或 postMessage 失败返回的 errMsg */
  441. function handleNativePickResult(res) {
  442. try {
  443. if (res && res.errMsg) {
  444. showFaultModal('原生调用失败', res.errMsg);
  445. return;
  446. }
  447. uploadNativePath(nativeTempPath(res));
  448. } catch (e) {
  449. showFaultModal('处理原生选择结果时异常', e);
  450. }
  451. }
  452. function uploadNativePath(filePath) {
  453. try {
  454. if (!filePath) {
  455. showFaultModal('未获取到文件路径', '壳子未返回 tempFilePath / tempFilePaths,或用户取消选择');
  456. return;
  457. }
  458. var uploadUrl = window.location.origin + '/api/attachment_test/upload';
  459. var timeoutId = setTimeout(function () {
  460. showLoading(false);
  461. showFaultModal('上传超时', '120 秒内未完成。请检查 App 是否实现 uploadFile、接口是否可达、Cookie 是否携带');
  462. }, 120000);
  463. showLoading(true);
  464. imSDK.uploadFile({
  465. url: uploadUrl,
  466. filePath: filePath,
  467. name: 'file',
  468. success: function (res) {
  469. try {
  470. clearTimeout(timeoutId);
  471. showLoading(false);
  472. if (res && res.errMsg) {
  473. showFaultModal('上传通道失败', res.errMsg);
  474. return;
  475. }
  476. var data = parseNativeUploadResponse(res);
  477. if (data && data.success) {
  478. showMessage(data.message || '上传成功');
  479. renderPreview({
  480. has_file: true,
  481. filename: data.filename,
  482. url: data.url
  483. });
  484. } else {
  485. showFaultModal('服务器返回失败', (data && data.message) ? data.message : JSON.stringify(data));
  486. }
  487. } catch (e) {
  488. showLoading(false);
  489. clearTimeout(timeoutId);
  490. showFaultModal('解析上传结果异常', e);
  491. }
  492. }
  493. });
  494. } catch (e) {
  495. showLoading(false);
  496. showFaultModal('发起原生上传异常', e);
  497. }
  498. }
  499. function renderPreview(data) {
  500. currentUrl = data.url || '';
  501. currentFilename = data.filename || '';
  502. urlBox.style.display = 'none';
  503. urlBox.textContent = '';
  504. if (!data.has_file || !data.url) {
  505. previewWrap.className = 'attachment-preview-wrap empty';
  506. previewWrap.textContent = '暂无附件,请使用上方按钮上传';
  507. previewActions.style.display = 'none';
  508. return;
  509. }
  510. previewWrap.className = 'attachment-preview-wrap';
  511. previewWrap.innerHTML = '';
  512. if (isImageName(data.filename)) {
  513. const img = document.createElement('img');
  514. img.src = data.url;
  515. img.alt = data.filename;
  516. previewWrap.appendChild(img);
  517. } else if (isVideoName(data.filename)) {
  518. const v = document.createElement('video');
  519. v.src = data.url;
  520. v.controls = true;
  521. v.playsInline = true;
  522. previewWrap.appendChild(v);
  523. } else {
  524. const p = document.createElement('p');
  525. p.textContent = '已上传文件(非预览类型)';
  526. previewWrap.appendChild(p);
  527. }
  528. const meta = document.createElement('div');
  529. meta.className = 'attachment-file-meta';
  530. meta.textContent = data.filename;
  531. previewWrap.appendChild(meta);
  532. previewActions.style.display = 'flex';
  533. }
  534. async function refreshStatus() {
  535. try {
  536. const r = await fetch('/api/attachment_test/status');
  537. const data = await r.json();
  538. if (data.success) {
  539. renderPreview(data);
  540. }
  541. } catch (e) {
  542. showFaultModal('加载附件状态失败', e);
  543. }
  544. }
  545. async function uploadFile(file) {
  546. if (!file) return;
  547. const fd = new FormData();
  548. fd.append('file', file);
  549. showLoading(true);
  550. try {
  551. const r = await fetch('/api/attachment_test/upload', { method: 'POST', body: fd });
  552. const data = await r.json();
  553. if (data.success) {
  554. showMessage(data.message || '上传成功');
  555. renderPreview({
  556. has_file: true,
  557. filename: data.filename,
  558. url: data.url,
  559. });
  560. } else {
  561. showFaultModal('上传被拒绝', data.message || JSON.stringify(data));
  562. }
  563. } catch (e) {
  564. showFaultModal('浏览器上传失败', e);
  565. } finally {
  566. showLoading(false);
  567. clearInputs();
  568. }
  569. }
  570. function wireInput(id) {
  571. const el = document.getElementById(id);
  572. if (!el) return;
  573. el.addEventListener('change', function () {
  574. const f = this.files && this.files[0];
  575. if (!f) return;
  576. uploadFile(f);
  577. });
  578. }
  579. ['inpCameraPhoto', 'inpCameraVideo', 'inpGalleryImage', 'inpGalleryVideo', 'inpAnyFile'].forEach(wireInput);
  580. function triggerFileInput(id) {
  581. try {
  582. var el = document.getElementById(id);
  583. if (el) el.click();
  584. } catch (e) {
  585. showFaultModal('无法打开文件选择', e);
  586. }
  587. }
  588. document.getElementById('btnCameraPhoto').addEventListener('click', function () {
  589. try {
  590. if (useUniNative()) {
  591. imSDK.chooseImage({
  592. count: 1,
  593. sourceType: ['camera'],
  594. success: handleNativePickResult
  595. });
  596. } else {
  597. triggerFileInput('inpCameraPhoto');
  598. }
  599. } catch (e) {
  600. showFaultModal('拍照', e);
  601. }
  602. });
  603. document.getElementById('btnCameraVideo').addEventListener('click', function () {
  604. try {
  605. if (useUniNative()) {
  606. imSDK.chooseVideo({
  607. sourceType: ['camera'],
  608. maxDuration: 120,
  609. camera: 'back',
  610. success: handleNativePickResult
  611. });
  612. } else {
  613. triggerFileInput('inpCameraVideo');
  614. }
  615. } catch (e) {
  616. showFaultModal('拍视频', e);
  617. }
  618. });
  619. document.getElementById('btnGalleryImage').addEventListener('click', function () {
  620. try {
  621. if (useUniNative()) {
  622. imSDK.chooseImage({
  623. count: 1,
  624. sourceType: ['album'],
  625. success: handleNativePickResult
  626. });
  627. } else {
  628. triggerFileInput('inpGalleryImage');
  629. }
  630. } catch (e) {
  631. showFaultModal('相册图片', e);
  632. }
  633. });
  634. document.getElementById('btnGalleryVideo').addEventListener('click', function () {
  635. try {
  636. if (useUniNative()) {
  637. imSDK.chooseVideo({
  638. sourceType: ['album'],
  639. maxDuration: 120,
  640. camera: 'back',
  641. success: handleNativePickResult
  642. });
  643. } else {
  644. triggerFileInput('inpGalleryVideo');
  645. }
  646. } catch (e) {
  647. showFaultModal('相册视频', e);
  648. }
  649. });
  650. document.getElementById('btnAnyFile').addEventListener('click', function () {
  651. try {
  652. if (useUniNative()) {
  653. imSDK.chooseFile({
  654. count: 1,
  655. extension: [],
  656. success: function (res) {
  657. try {
  658. if (res && res.errMsg) {
  659. showFaultModal('原生选择文件失败', res.errMsg);
  660. return;
  661. }
  662. var path = nativeTempPath(res);
  663. if (!path && res.tempFiles && res.tempFiles[0]) path = res.tempFiles[0].path;
  664. uploadNativePath(path);
  665. } catch (e) {
  666. showFaultModal('处理选择文件结果异常', e);
  667. }
  668. }
  669. });
  670. } else {
  671. triggerFileInput('inpAnyFile');
  672. }
  673. } catch (e) {
  674. showFaultModal('选择文件', e);
  675. }
  676. });
  677. document.getElementById('btnShare').addEventListener('click', async function () {
  678. try {
  679. if (!currentUrl) {
  680. showFaultModal('无法分享', '当前没有可分享的附件链接,请先上传');
  681. return;
  682. }
  683. if (navigator.share) {
  684. try {
  685. await navigator.share({ title: '附件链接', text: currentFilename, url: currentUrl });
  686. return;
  687. } catch (e) {
  688. if (e.name === 'AbortError') return;
  689. console.warn('[attachment-test] share failed, fallback clipboard', e);
  690. }
  691. }
  692. try {
  693. await navigator.clipboard.writeText(currentUrl);
  694. showMessage('链接已复制到剪贴板');
  695. } catch (e) {
  696. urlBox.style.display = 'block';
  697. urlBox.textContent = currentUrl;
  698. showFaultModal('复制链接失败', e);
  699. }
  700. } catch (e) {
  701. showFaultModal('分享', e);
  702. }
  703. });
  704. document.getElementById('btnDelete').addEventListener('click', async function () {
  705. if (!confirm('确定删除当前附件?')) return;
  706. showLoading(true);
  707. try {
  708. const r = await fetch('/api/attachment_test', { method: 'DELETE' });
  709. const data = await r.json();
  710. if (data.success) {
  711. showMessage(data.message || '已删除');
  712. renderPreview({ has_file: false });
  713. } else {
  714. showFaultModal('删除失败', data.message || JSON.stringify(data));
  715. }
  716. } catch (e) {
  717. showFaultModal('删除请求异常', e);
  718. } finally {
  719. showLoading(false);
  720. }
  721. });
  722. window.addEventListener('unhandledrejection', function (ev) {
  723. console.error('[attachment-test] unhandledrejection', ev.reason);
  724. showFaultModal('未处理的 Promise 异常', ev.reason instanceof Error ? ev.reason : String(ev.reason));
  725. });
  726. refreshStatus();
  727. })();
  728. </script>
  729. {% endblock %}