Skip to content

Commit

Permalink
feat: Add file upload and deletion functionality
Browse files Browse the repository at this point in the history
This commit adds the ability to upload and delete files in the useDirectusFiles composable. The new functions, uploadFiles and deleteFiles, allow users to upload single or multiple files and delete files by their ID. This enhances the functionality of the composable and provides more flexibility for managing files.
  • Loading branch information
yavuz committed Nov 16, 2024
1 parent 5d4af61 commit f805a9e
Showing 1 changed file with 63 additions and 1 deletion.
64 changes: 63 additions & 1 deletion src/runtime/composables/useDirectusFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,67 @@ export const useDirectusFiles = () => {
return url.href
}

return { getFiles, getThumbnail }
const uploadFiles = async (fileData, options = {}) => {
try {
const formData = new FormData();

if (Array.isArray(fileData)) {
fileData.forEach((file) => {
formData.append('file[]', file);
});
} else {
formData.append('file', fileData);
}

const uploadResponse = await directus("/files", {
method: "POST",
body: formData
});

const fileId = uploadResponse.data.id;

if (options.title || options.tags) {
const updateData = {};
if (options.title) updateData.title = options.title;
if (options.tags) updateData.tags = options.tags;

await directus(`/files/${fileId}`, {
method: "PATCH",
body: updateData
});

const updatedFile = await directus(`/files/${fileId}`, {
method: "GET"
});

return updatedFile.data;
}

return uploadResponse.data;

} catch (error) {
console.error('File upload error:', error);
throw error;
}
};

const deleteFiles = async (fileId) => {
try {
if (Array.isArray(fileId)) {
await directus("/files", {
method: "DELETE",
body: fileId
});
} else {
await directus(`/files/${fileId}`, {
method: "DELETE"
});
}
} catch (error) {
console.error('File upload error:', error);
throw error;
}
};

return { getFiles, getThumbnail, uploadFiles, deleteFiles }
}

0 comments on commit f805a9e

Please sign in to comment.