Files
online-energieausweis/src/components/UploadImages.svelte
2024-01-12 14:26:15 +07:00

98 lines
2.4 KiB
Svelte

<script lang="ts">
import { BedarfsausweisWohnen, VerbrauchsausweisGewerbe, VerbrauchsausweisWohnen } from "@ibcornelsen/database";
export let max: number = 2;
// Array of base64 encoded images read into the input.
export let images: (File & { data: string })[] = [];
export let ausweis: VerbrauchsausweisWohnen | VerbrauchsausweisGewerbe | BedarfsausweisWohnen;
function getAllImages(this: HTMLInputElement) {
const files = this.files || [];
if (images.length == max) {
this.value = "";
return;
}
for (let i = 0; i < files.length; i++) {
const file = files[i];
if ((file.type !== "image/jpeg") && (file.type !== "image/png")) {
i--;
continue;
}
if (i == max) {
break;
}
const reader = new FileReader();
reader.onload = (ev) => {
if (reader.readyState != reader.DONE) {
return;
}
if (!reader.result) {
return;
}
let blob = new Blob([reader.result as ArrayBuffer]);
let url = URL.createObjectURL(blob);
let image = new Image();
image.onload = () => {
// Create a new canvas with the desired output size
const canvas = document.createElement("canvas");
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
// Scale down the image and draw it onto the canvas
const ctx = canvas.getContext("2d");
if (!ctx) {
return;
}
ctx.drawImage(image, 0, 0, image.naturalWidth, image.naturalHeight);
// Get the scaled-down data from the canvas in the desired output format and quality
const dataURL = canvas.toDataURL("image/jpeg", 0.8);
fetch("/api/image.json", {
method: "PUT",
body: JSON.stringify({
data: dataURL.split(';base64,')[1],
name: file.name,
kategorie: "",
gebaeude_uid: ausweis.gebaeude_stammdaten_id
})
}).then(response => response.json()).then(json => {
if (json.success === false) {
return
}
images.push({ ...file, data: dataURL as string } as (File & { data: string }));
images = images;
ausweis.uid = json.data.gebaeude_uid;
})
if (i == (Math.min(files.length, max) - 1)) {
this.value = "";
}
}
image.src = url;
}
reader.readAsArrayBuffer(file);
}
}
</script>
{#if max > 1}
<input type="file" multiple on:change={getAllImages} />
{:else}
<input type="file" on:change={getAllImages} />
{/if}