使用Multer与Cloudinary Node.js API上传文件时临时文件提前删除问题
问题解决:Multer+Cloudinary上传时临时文件提前被删除
问题根源
核心问题是文件删除操作未正确等待Cloudinary上传完成,大概率是因为使用了回调式的fs.unlink而非Promise版本,导致await无法生效,删除操作提前执行,打断了Cloudinary的文件读取流程。此外,代码中对Cloudinary返回结果的处理也存在错误(直接将对象转为字符串)。
解决方案
1. 使用Promise版本的文件删除方法
Node.js的fs模块提供了Promise化的API,替换原有的回调式unlink,确保await能正确等待删除操作完成:
// 导入fs模块(CommonJS语法) const fs = require('fs'); // 或ES Modules语法 import fs from 'fs';
2. 修正上传与删除的逻辑
确保Cloudinary上传完成后再执行删除,同时正确提取Cloudinary返回的文件URL:
海报上传部分修正
if (files?.poster?.length) { posterPath = files?.poster[0]?.path || ""; try { const uploadResult = await uploader.upload(posterPath, options); // 等待上传完成后再删除本地文件 await fs.promises.unlink(posterPath); // 提取Cloudinary返回的安全URL posterPath = uploadResult.secure_url; } catch (err) { console.error('海报上传失败:', err); // 上传失败也要清理本地文件 await fs.promises.unlink(posterPath); posterPath = ""; } }
视频上传部分修正
if (files?.video?.length) { videoPath = files?.video[0]?.path || ""; try { const uploadResult = await uploader.upload(videoPath, { ...options, resource_type: "video", }); await fs.promises.unlink(videoPath); videoPath = uploadResult.secure_url; } catch (err) { console.error('视频上传失败:', err); await fs.promises.unlink(videoPath); videoPath = ""; } }
3. 额外注意事项
- Cloudinary的
uploader.upload返回的是包含文件信息的对象,而非字符串,必须提取secure_url(或url)字段作为存储的路径。 - Multer默认会在路由处理前完成文件写入,无需额外处理这一步的异步等待。
内容的提问来源于stack exchange,提问作者Alexander P
相关产品推荐
相关产品推荐

