Files
AI-Chat/public/assets/js/upload.js
2026-05-06 18:25:44 +08:00

68 lines
1.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const UploadManager = {
files: [], // 待发送的文件列表
allowedTypes: '.jpg,.jpeg,.png,.gif,.webp,.js,.ts,.py,.java,.cpp,.c,.html,.css,.json,.xml,.txt,.md,.go,.rs,.php,.rb,.sql,.yaml,.yml,.sh,.bat',
init() {
const btn = document.getElementById('uploadBtn');
if (btn) {
btn.addEventListener('click', () => this.openFileSelector());
}
},
openFileSelector() {
const input = document.createElement('input');
input.type = 'file';
input.accept = this.allowedTypes;
input.multiple = true;
input.onchange = (e) => this.handleFiles(e.target.files);
input.click();
},
async handleFiles(fileList) {
for (const file of fileList) {
const formData = new FormData();
formData.append('file', file);
try {
const res = await api.upload('/upload', formData);
this.files.push(res.data);
this.renderPreview();
} catch (err) {
alert('文件上传失败: ' + err.message);
}
}
},
renderPreview() {
const preview = document.getElementById('filePreview');
if (!preview) return;
preview.innerHTML = this.files.map((f, i) => `
<div class="file-preview-item">
<span>${this.escapeHtml(f.name)}</span>
<span class="remove-file" onclick="UploadManager.removeFile(${i})">×</span>
</div>
`).join('');
},
removeFile(index) {
this.files.splice(index, 1);
this.renderPreview();
},
getFiles() {
return this.files;
},
clearFiles() {
this.files = [];
this.renderPreview();
},
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
};