remix-asset-upload.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. function registerRemixAssetUploadRoutes(app, deps) {
  2. const {
  3. path,
  4. assetUpload,
  5. qiniuUploadUrl,
  6. qiniuCdnDomain,
  7. buildDigitalHumanAssetKey,
  8. buildQiniuUploadToken,
  9. } = deps;
  10. app.post('/api/remix/upload-asset', assetUpload.single('file'), async (req, res) => {
  11. try {
  12. if (!req.file) {
  13. return res.status(400).json({ error: '未收到素材文件' });
  14. }
  15. const mimeType = req.file.mimetype || 'application/octet-stream';
  16. const kind = mimeType.startsWith('audio/')
  17. ? 'audio'
  18. : mimeType.startsWith('video/')
  19. ? 'video'
  20. : 'image';
  21. const key = buildDigitalHumanAssetKey(req.file.originalname, kind);
  22. const token = buildQiniuUploadToken(key);
  23. const formData = new FormData();
  24. formData.append('token', token);
  25. formData.append('key', key);
  26. formData.append('file', new Blob([req.file.buffer], { type: mimeType }), path.basename(key));
  27. const response = await fetch(qiniuUploadUrl, {
  28. method: 'POST',
  29. body: formData,
  30. });
  31. const text = await response.text();
  32. let payload = null;
  33. try {
  34. payload = text ? JSON.parse(text) : null;
  35. } catch {
  36. payload = null;
  37. }
  38. if (!response.ok) {
  39. return res.status(response.status).json({
  40. error: payload?.error || payload?.message || text || '七牛素材上传失败',
  41. detail: payload || text || '',
  42. });
  43. }
  44. const uploadedKey = payload?.key || key;
  45. const url = `${qiniuCdnDomain.replace(/\/$/, '')}/${uploadedKey}`;
  46. if (!uploadedKey || !url) {
  47. return res.status(500).json({ error: '七牛未返回素材 Key', detail: payload || text || '' });
  48. }
  49. res.json({
  50. success: true,
  51. url,
  52. key: uploadedKey,
  53. mimeType,
  54. kind,
  55. });
  56. } catch (error) {
  57. console.error('❌ 上传重塑素材失败:', error);
  58. res.status(500).json({ error: `上传重塑素材失败: ${error.message}` });
  59. }
  60. });
  61. }
  62. module.exports = { registerRemixAssetUploadRoutes };