31 lines
858 B
TypeScript
31 lines
858 B
TypeScript
import type { APIContext } from "astro";
|
|
import sharp from "sharp";
|
|
import { join as joinPath } from "path";
|
|
|
|
function randomHash() {
|
|
return (Math.random() * 1e30).toString(16);
|
|
}
|
|
|
|
export async function post({ request }: APIContext) {
|
|
const response: { success: number; file?: { url: string } } = {
|
|
success: 1,
|
|
};
|
|
|
|
try {
|
|
const fd = await request.formData();
|
|
const imageFile = fd.get("image") as Blob;
|
|
const fName = `${randomHash()}_${imageFile.name}.jpg`;
|
|
await sharp(await imageFile.arrayBuffer())
|
|
.jpeg({ mozjpeg: true })
|
|
.toFile(joinPath(process.cwd(), "public", "uploads", fName));
|
|
response.file = {
|
|
url: `/uploads/${fName}`,
|
|
};
|
|
} catch (e) {
|
|
response.success = 0;
|
|
}
|
|
|
|
return {
|
|
body: JSON.stringify(response),
|
|
};
|
|
}
|