mirror of
https://github.com/seanmorley15/AdventureLog.git
synced 2025-08-05 05:05:17 +02:00
Object auto delete when upload
This commit is contained in:
parent
d27971692d
commit
157d9fe99c
2 changed files with 25 additions and 2 deletions
|
@ -1,5 +1,6 @@
|
|||
import {
|
||||
CreateBucketCommand,
|
||||
DeleteObjectCommand,
|
||||
HeadBucketCommand,
|
||||
PutBucketPolicyCommand,
|
||||
PutObjectCommand,
|
||||
|
@ -119,3 +120,20 @@ export const uploadObject = async (
|
|||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteObject = async (bucketName: string, fileName: string) => {
|
||||
const deleteObjectCommand = new DeleteObjectCommand({
|
||||
Bucket: bucketName,
|
||||
Key: fileName,
|
||||
});
|
||||
|
||||
try {
|
||||
await s3Client.send(deleteObjectCommand);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`Error uploading file ${fileName} to bucket ${bucketName}:`,
|
||||
error
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
// src/routes/api/upload.js
|
||||
|
||||
import { ensureBucketExists, uploadObject } from "$lib/server/s3";
|
||||
import { deleteObject, ensureBucketExists, uploadObject } from "$lib/server/s3";
|
||||
import type { RequestEvent } from "@sveltejs/kit";
|
||||
import { generateId } from "lucia";
|
||||
|
||||
|
@ -8,7 +8,7 @@ export async function POST(event: RequestEvent): Promise<Response> {
|
|||
try {
|
||||
const contentType = event.request.headers.get("content-type") ?? "";
|
||||
const fileExtension = contentType.split("/").pop();
|
||||
const fileName = `${generateId(25)}.${fileExtension}`;
|
||||
const fileName = `${generateId(50)}.${fileExtension}`;
|
||||
const bucket = event.request.headers.get("bucket") as string;
|
||||
|
||||
if (!fileExtension || !fileName) {
|
||||
|
@ -49,6 +49,11 @@ export async function POST(event: RequestEvent): Promise<Response> {
|
|||
|
||||
await ensureBucketExists(bucket);
|
||||
|
||||
if (event.locals.user?.icon) {
|
||||
const key: string = event.locals.user.icon.split("/").pop() as string;
|
||||
await deleteObject(bucket, key);
|
||||
}
|
||||
|
||||
const objectUrl = await uploadObject(
|
||||
bucket,
|
||||
fileName,
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue