feat: 实现多部分上传功能,支持初始化、上传部分、完成和中止上传,添加媒体资产删除功能
This commit is contained in:
@@ -3,12 +3,62 @@ import { request } from '../utils/request';
|
||||
export const commonApi = {
|
||||
getOptions: () => request('/common/options'),
|
||||
checkHash: (hash) => request(`/upload/check?hash=${hash}`),
|
||||
deleteMedia: (id) => request(`/media-assets/${id}`, { method: 'DELETE' }),
|
||||
upload: (file, type) => {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('type', type);
|
||||
return request('/upload', { method: 'POST', body: formData });
|
||||
},
|
||||
uploadMultipart: async (file, hash, onProgress) => {
|
||||
// 1. Check Hash
|
||||
try {
|
||||
const res = await commonApi.checkHash(hash);
|
||||
if (res) {
|
||||
if (onProgress) onProgress(100);
|
||||
return res;
|
||||
}
|
||||
} catch(e) {}
|
||||
|
||||
// 2. Init
|
||||
const initRes = await request('/upload/init', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
filename: file.name,
|
||||
size: file.size,
|
||||
mime_type: file.type,
|
||||
hash: hash
|
||||
}
|
||||
});
|
||||
|
||||
const { upload_id, chunk_size } = initRes;
|
||||
const totalChunks = Math.ceil(file.size / chunk_size);
|
||||
|
||||
// 3. Upload Parts
|
||||
for (let i = 0; i < totalChunks; i++) {
|
||||
const start = i * chunk_size;
|
||||
const end = Math.min(start + chunk_size, file.size);
|
||||
const chunk = file.slice(start, end);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('file', chunk);
|
||||
formData.append('upload_id', upload_id);
|
||||
formData.append('part_number', i + 1);
|
||||
|
||||
await request('/upload/part', { method: 'POST', body: formData });
|
||||
|
||||
if (onProgress) {
|
||||
const percent = Math.round(((i + 1) / totalChunks) * 100);
|
||||
onProgress(percent);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Complete
|
||||
return request('/upload/complete', {
|
||||
method: 'POST',
|
||||
body: { upload_id }
|
||||
});
|
||||
},
|
||||
uploadWithProgress: (file, type, onProgress) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const formData = new FormData();
|
||||
|
||||
Reference in New Issue
Block a user