74 lines
2.2 KiB
JavaScript
74 lines
2.2 KiB
JavaScript
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;
|
||
}
|
||
};
|