From c9aaf502af2c25935a0a1c0d706a9a701d4db51c Mon Sep 17 00:00:00 2001 From: Danny Avila <110412045+danny-avila@users.noreply.github.com> Date: Sun, 7 Jan 2024 15:22:33 -0500 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(saveImageFromUrl):=20Dynamic?= =?UTF-8?q?=20Extension=20Handling=20(#1514)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Enhanced the `saveImageFromUrl` function to dynamically handle file extensions based on the content type of the fetched image. - Replaced the method of appending a '.png' extension with a more robust approach using regular expressions and the path module. - Allows for correct extension replacement or addition, ensuring filename consistency and compatibility with the actual image format. - Prevents issues with double extensions (e.g., 'someimage.jpg.png') and aligns saved file types with their respective content types. --- api/app/clients/tools/saveImageFromUrl.js | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/api/app/clients/tools/saveImageFromUrl.js b/api/app/clients/tools/saveImageFromUrl.js index d8b14ad478..b9fbcc895b 100644 --- a/api/app/clients/tools/saveImageFromUrl.js +++ b/api/app/clients/tools/saveImageFromUrl.js @@ -11,18 +11,24 @@ async function saveImageFromUrl(url, outputPath, outputFilename) { responseType: 'stream', }); + // Get the content type from the response headers + const contentType = response.headers['content-type']; + let extension = contentType.split('/').pop(); + // Check if the output directory exists, if not, create it if (!fs.existsSync(outputPath)) { fs.mkdirSync(outputPath, { recursive: true }); } - // Ensure the output filename has a '.png' extension - const filenameWithPngExt = outputFilename.endsWith('.png') - ? outputFilename - : `${outputFilename}.png`; + // Replace or append the correct extension + const extRegExp = new RegExp(path.extname(outputFilename) + '$'); + outputFilename = outputFilename.replace(extRegExp, `.${extension}`); + if (!path.extname(outputFilename)) { + outputFilename += `.${extension}`; + } // Create a writable stream for the output path - const outputFilePath = path.join(outputPath, filenameWithPngExt); + const outputFilePath = path.join(outputPath, outputFilename); const writer = fs.createWriteStream(outputFilePath); // Pipe the response data to the output file