Stirling-PDF/frontend/src/utils/fileResponseUtils.ts
ConnorYoh 47ccb6a6ed
improvement/v2/automate/tweaks (#4293)
- [x] Cleanup Automation output name garbage			
- [x] Remove Cross button on first two tools			
- [x] Automation creation name title to make clearer to the user
- [x] Colours for dark mode on automation tool settings are bad 	
- [x] Fix tool names not using correct translated ones 
- [x] suggested Automation Password needs adding to description 
- [x] Allow different filetypes in automation
- [x] Custom Icons for automation
- [x] split Tool wasn't working with merge to single pdf

---------

Co-authored-by: Connor Yoh <connor@stirlingpdf.com>
Co-authored-by: James Brunton <jbrunton96@gmail.com>
2025-08-26 16:59:03 +01:00

45 lines
1.5 KiB
TypeScript

/**
* Generic utility functions for handling file responses from API endpoints
*/
/**
* Extracts filename from Content-Disposition header
* @param contentDisposition - Content-Disposition header value
* @returns Filename if found, null otherwise
*/
export const getFilenameFromHeaders = (contentDisposition: string = ''): string | null => {
const match = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
if (match && match[1]) {
const filename = match[1].replace(/['"]/g, '');
// Decode URL-encoded characters (e.g., %20 -> space)
try {
return decodeURIComponent(filename);
} catch (error) {
// If decoding fails, return the original filename
return filename;
}
}
return null;
};
/**
* Creates a File object from API response using the filename from headers
* @param responseData - The response data (blob/arraybuffer/string)
* @param headers - Response headers object
* @param fallbackFilename - Filename to use if none provided in headers
* @returns File object
*/
export const createFileFromApiResponse = (
responseData: any,
headers: any,
fallbackFilename: string
): File => {
const contentType = headers?.['content-type'] || 'application/octet-stream';
const contentDisposition = headers?.['content-disposition'] || '';
const filename = getFilenameFromHeaders(contentDisposition) || fallbackFilename;
const blob = new Blob([responseData], { type: contentType });
return new File([blob], filename, { type: contentType });
};