Browse Source

fix(upload): resolve file path conflicts during image conversion

- Updated the image upload handler to prevent conflicts when the input and output paths are the same, particularly for webp images.
- Introduced a temporary output path for converted images, ensuring the original file is preserved during processing.
- Enhanced error handling to clean up temporary files and maintain the integrity of the final output.

These changes improve the reliability of the image upload process and prevent potential file overwrites.
main
npmrun 2 weeks ago
parent
commit
374fcbfadb
  1. BIN
      packages/drizzle-pkg/db.sqlite
  2. 19
      server/api/file/upload.post.ts

BIN
packages/drizzle-pkg/db.sqlite

Binary file not shown.

19
server/api/file/upload.post.ts

@ -102,6 +102,8 @@ export default defineWrappedResponseHandler(async (event) => {
const stem = path.parse(file.filename).name; const stem = path.parse(file.filename).name;
const finalName = `${stem}.webp`; const finalName = `${stem}.webp`;
const finalPath = path.join(uploadDir, finalName); const finalPath = path.join(uploadDir, finalName);
// sharp 不允许输入与输出指向同一路径(常见于原图本身就是 webp)
const tempOutputPath = file.path === finalPath ? path.join(uploadDir, `${stem}-converted.webp`) : finalPath;
try { try {
await sharp(file.path) await sharp(file.path)
@ -113,11 +115,11 @@ export default defineWrappedResponseHandler(async (event) => {
withoutEnlargement: true, withoutEnlargement: true,
}) })
.webp({ quality: MEDIA_WEBP_QUALITY }) .webp({ quality: MEDIA_WEBP_QUALITY })
.toFile(finalPath); .toFile(tempOutputPath);
} catch (procErr) { } catch (procErr) {
if (fs.existsSync(finalPath)) { if (fs.existsSync(tempOutputPath)) {
try { try {
fs.unlinkSync(finalPath); fs.unlinkSync(tempOutputPath);
} catch { } catch {
/* ignore */ /* ignore */
} }
@ -126,6 +128,17 @@ export default defineWrappedResponseHandler(async (event) => {
throw createError({ statusCode: 400, statusMessage: msg }); throw createError({ statusCode: 400, statusMessage: msg });
} }
if (tempOutputPath !== finalPath) {
if (fs.existsSync(finalPath)) {
try {
fs.unlinkSync(finalPath);
} catch {
/* ignore */
}
}
fs.renameSync(tempOutputPath, finalPath);
}
if (file.path !== finalPath) { if (file.path !== finalPath) {
try { try {
fs.unlinkSync(file.path); fs.unlinkSync(file.path);

Loading…
Cancel
Save