DFiP_Budget_planing/web/src/utils/downloadFile.js
2026-05-18 17:33:45 +03:00

74 lines
2.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

export const downloadFile = async (
response,
defaultFilename = 'download',
defaultExtension = 'bin',
) => {
try {
if (response.status < 200 || response.status >= 300) {
throw new Error(`HTTP error ${response.status}`);
}
if (defaultExtension !== 'csv' && !(response.data instanceof Blob)) {
throw new Error('Неверный формат ответа');
}
const blob = response.data;
const contentType = response.headers['content-type'] || '';
// Функция для определения расширения по Content-Type
const getExtensionFromContentType = (type) => {
const typeMap = {
zip: ['application/zip', 'application/x-zip-compressed'],
xlsx: [
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
],
xls: ['application/vnd.ms-excel'],
csv: ['text/csv', 'text/comma-separated-values'],
pdf: ['application/pdf'],
docx: [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
],
doc: ['application/msword'],
json: ['application/json'],
txt: ['text/plain'],
xml: ['application/xml', 'text/xml'],
};
for (const [ext, types] of Object.entries(typeMap)) {
if (types.some((t) => type.includes(t))) {
return ext;
}
}
return null;
};
const date = new Date().toISOString().split('T')[0];
const ext = getExtensionFromContentType(contentType) || defaultExtension;
const filename = `${defaultFilename}_${date}.${ext}`;
// Создаем URL для blob с правильным типом
const blobWithType = new Blob([blob], {
type: contentType || blob.type || 'application/octet-stream',
});
const url = window.URL.createObjectURL(blobWithType);
// Создаем и кликаем по ссылке
const link = document.createElement('a');
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
setTimeout(() => {
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
}, 100);
return true;
} catch (error) {
console.error('Error downloading file:', error);
throw error;
}
};