79 lines
2.6 KiB
JavaScript
79 lines
2.6 KiB
JavaScript
import { request, getToken } from './client.js';
|
||
|
||
// client.request 走 JSON,上传必须独立走 fetch + FormData + Bearer
|
||
|
||
async function upload(path, file, extra, fieldName = 'file') {
|
||
const fd = new FormData();
|
||
fd.append(fieldName, file);
|
||
if (extra) {
|
||
for (const [k, v] of Object.entries(extra)) {
|
||
if (v !== undefined && v !== null && v !== '') fd.append(k, String(v));
|
||
}
|
||
}
|
||
const headers = {};
|
||
const token = getToken();
|
||
if (token) headers.Authorization = 'Bearer ' + token;
|
||
const res = await fetch('/api/upload' + path, { method: 'POST', headers, body: fd });
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) {
|
||
const err = new Error(data.error || '上传失败');
|
||
err.status = res.status;
|
||
throw err;
|
||
}
|
||
return data;
|
||
}
|
||
|
||
/** 普通文件上传;opts 可选 { ref_type, ref_id }。返回 { id, url, tag, ... },tag 为 [image:]/[file:] 插入文本 */
|
||
export function uploadFile(file, opts) {
|
||
return upload('/file', file, opts);
|
||
}
|
||
|
||
/** 头像上传,成功后直接更新用户 avatar,返回 { url } */
|
||
export function uploadAvatar(file) {
|
||
return upload('/avatar', file);
|
||
}
|
||
|
||
/** 壁纸上传,返回 { url, filename } */
|
||
export function uploadWallpaper(file) {
|
||
return upload('/wallpaper', file);
|
||
}
|
||
|
||
/** 版块图标上传(multipart 字段名 icon,≤1MB),返回 { url: '/uploads/icons/xxx.png' } */
|
||
export function uploadIcon(file) {
|
||
return upload('/icon', file, undefined, 'icon');
|
||
}
|
||
|
||
/** 按 uid 获取头像地址(支持 QQ 自动头像) */
|
||
export function avatarUrl(uid) {
|
||
return request('/upload/avatar-url?uid=' + encodeURIComponent(uid));
|
||
}
|
||
|
||
/** 附件列表;可按 ref_type + ref_id 过滤 */
|
||
export function listAttachments(refType, refId) {
|
||
const q = [];
|
||
if (refType && refId) {
|
||
q.push('ref_type=' + encodeURIComponent(refType), 'ref_id=' + encodeURIComponent(refId));
|
||
}
|
||
return request('/upload/list' + (q.length ? '?' + q.join('&') : ''));
|
||
}
|
||
|
||
/** 删除附件(本人或管理员) */
|
||
export function deleteAttachment(id) {
|
||
return request('/upload/' + id, { method: 'DELETE' });
|
||
}
|
||
|
||
/** 搜索引擎验证文件上传(仅管理员,multipart 字段名 file,≤64KB),返回 { url, message } */
|
||
export function uploadVerifyFile(file) {
|
||
return upload('/verify-file', file);
|
||
}
|
||
|
||
/** 已上传验证文件列表(仅管理员),返回 [{ name, url }] */
|
||
export function listVerifyFiles() {
|
||
return request('/upload/verify-files');
|
||
}
|
||
|
||
/** 删除验证文件(仅管理员),返回 { message } */
|
||
export function deleteVerifyFile(name) {
|
||
return request('/upload/verify-file/' + encodeURIComponent(name), { method: 'DELETE' });
|
||
}
|