51 lines
1.9 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.

import axios from 'axios';
import CONFIG from '@/core/config.js';
const downloadProjectFile = async (fileId) => {
try {
const token = localStorage.getItem('access_token');
const response = await axios.get(
`${CONFIG.BASE_URL}/project_files/${fileId}/download`,
{
headers: {
Authorization: `Bearer ${token}`,
},
responseType: 'blob',
withCredentials: true,
}
);
// Создаем ссылку для скачивания
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
const contentDisposition = response.headers['content-disposition'];
let filename = `project_file_${fileId}`;
if (contentDisposition) {
const filenameMatch = contentDisposition.match(/filename="([^"]+)"/);
if (filenameMatch && filenameMatch[1]) {
filename = decodeURIComponent(filenameMatch[1]);
}
}
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
link.remove();
window.URL.revokeObjectURL(url);
return { success: true, filename: filename };
} catch (error) {
const errorMessage = error.response?.data?.detail || error.message;
console.error(`Ошибка скачивания файла проекта с ID ${fileId}:`, errorMessage);
if (error.response?.status === 401) {
throw new Error("Недостаточно прав для скачивания файла (401)");
}
if (error.response?.status === 404) {
throw new Error("Файл не найден (404)");
}
throw new Error(errorMessage);
}
};
export default downloadProjectFile;