mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-12-17 00:40:14 +01:00
✨ feat(saveImageFromUrl): Dynamic Extension Handling (#1514)
- 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.
This commit is contained in:
parent
050a92b318
commit
c9aaf502af
1 changed files with 11 additions and 5 deletions
|
|
@ -11,18 +11,24 @@ async function saveImageFromUrl(url, outputPath, outputFilename) {
|
||||||
responseType: 'stream',
|
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
|
// Check if the output directory exists, if not, create it
|
||||||
if (!fs.existsSync(outputPath)) {
|
if (!fs.existsSync(outputPath)) {
|
||||||
fs.mkdirSync(outputPath, { recursive: true });
|
fs.mkdirSync(outputPath, { recursive: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure the output filename has a '.png' extension
|
// Replace or append the correct extension
|
||||||
const filenameWithPngExt = outputFilename.endsWith('.png')
|
const extRegExp = new RegExp(path.extname(outputFilename) + '$');
|
||||||
? outputFilename
|
outputFilename = outputFilename.replace(extRegExp, `.${extension}`);
|
||||||
: `${outputFilename}.png`;
|
if (!path.extname(outputFilename)) {
|
||||||
|
outputFilename += `.${extension}`;
|
||||||
|
}
|
||||||
|
|
||||||
// Create a writable stream for the output path
|
// 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);
|
const writer = fs.createWriteStream(outputFilePath);
|
||||||
|
|
||||||
// Pipe the response data to the output file
|
// Pipe the response data to the output file
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue