Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

rewrite uploader error handling

Oleg Isonen12d6782d36d8
diff --git a/apps/designer/app/designer/shared/assets/asset-upload.tsx b/apps/designer/app/designer/shared/assets/asset-upload.tsx
index 76c2e0a870..165d7c72d1 100644
--- a/apps/designer/app/designer/shared/assets/asset-upload.tsx
+++ b/apps/designer/app/designer/shared/assets/asset-upload.tsx
@@ -1,56 +1,89 @@
-import { Form, useActionData } from "@remix-run/react";
+import { Form, FormEncType, FormMethod, useActionData } from "@remix-run/react";
import ObjectID from "bson-objectid";
import { ChangeEvent, useEffect, useRef } from "react";
-import { Button, Flex, Text } from "@webstudio-is/design-system";
+import { Button, Flex, Text, toast } from "@webstudio-is/design-system";
import { UploadIcon } from "@webstudio-is/icons";
-import { type AssetType } from "@webstudio-is/asset-uploader";
+import {
+ MAX_UPLOAD_SIZE,
+ toBytes,
+ type AssetType,
+} from "@webstudio-is/asset-uploader";
import type { ActionData, PreviewAsset } from "./types";
import { FONT_MIME_TYPES } from "@webstudio-is/fonts";
import { useSerialSubmit } from "./use-serial-submit";
-const toPreviewAssets = (fileList: FileList): Promise<PreviewAsset[]> => {
- const assets: Array<Promise<PreviewAsset>> = Array.from(fileList).map(
- (file) =>
- new Promise((resolve, reject) => {
- const reader = new FileReader();
- reader.addEventListener("load", (event) => {
- const dataUri = event?.target?.result;
- if (dataUri === undefined) {
- return reject(new Error("Could not read file"));
- }
+const toPreviewAssets = (formData: FormData): Promise<PreviewAsset[]> => {
+ const assets: Array<Promise<PreviewAsset>> = [];
+
+ for (const entry of formData) {
+ const file = entry[1] as File;
+ const promise: Promise<PreviewAsset> = new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.addEventListener("load", (event) => {
+ const dataUri = event?.target?.result;
+ if (dataUri === undefined) {
+ return reject(new Error(`Could not read file "${file.name}"`));
+ }
- resolve({
- format: file.type.split("/")[1],
- path: String(dataUri),
- name: file.name,
- id: ObjectID().toString(),
- status: "uploading",
- });
+ resolve({
+ format: file.type.split("/")[1],
+ path: String(dataUri),
+ name: file.name,
+ id: ObjectID().toString(),
+ status: "uploading",
});
- reader.readAsDataURL(file);
- })
- );
+ });
+ reader.readAsDataURL(file);
+ });
+ assets.push(promise);
+ }
return Promise.all(assets);
};
+const maxSize = toBytes(MAX_UPLOAD_SIZE);
+
const useUpload = ({
onSubmit,
onActionData,
+ type,
}: {
onActionData: (data: ActionData) => void;
onSubmit: (assets: Array<PreviewAsset>) => void;
+ type: AssetType;
}) => {
const submit = useSerialSubmit();
const inputRef = useRef<HTMLInputElement | null>(null);
const actionData: ActionData | undefined = useActionData();
const onChange = (event: ChangeEvent<HTMLFormElement>) => {
- const files = inputRef?.current?.files;
- if (files && files.length !== 0) {
- submit(event.currentTarget);
- toPreviewAssets(files).then(onSubmit);
- event.currentTarget.reset();
+ const files = Array.from(inputRef?.current?.files ?? []);
+ if (files.length !== 0) {
+ const form = event.currentTarget;
+ const formData = new FormData();
+ for (const file of files) {
+ if (file.size > maxSize) {
+ toast.error(
+ `Asset "${file.name}" cannot be bigger than ${MAX_UPLOAD_SIZE}MB`
+ );
+ continue;
+ }
+ formData.append(type, file, file.name);
+ }
+ const options = {
+ method: form.method as FormMethod,
+ action: form.action,
+ encType: form.enctype as FormEncType,
+ };
+ submit(formData, options);
+ toPreviewAssets(formData)
+ .then(onSubmit)
+ .catch((error: unknown) => {
+ if (error instanceof Error) {
+ toast.error(error.message);
+ }
+ });
+ form.reset();
}
};
@@ -79,7 +112,7 @@ export const AssetUpload = ({
onActionData,
type,
}: AssetUploadProps) => {
- const { inputRef, onChange } = useUpload({ onSubmit, onActionData });
+ const { inputRef, onChange } = useUpload({ onSubmit, onActionData, type });
return (
<Flex
as={Form}
diff --git a/apps/designer/app/designer/shared/assets/use-serial-submit.ts b/apps/designer/app/designer/shared/assets/use-serial-submit.ts
index be89611d9f..c74cf5a602 100644
--- a/apps/designer/app/designer/shared/assets/use-serial-submit.ts
+++ b/apps/designer/app/designer/shared/assets/use-serial-submit.ts
@@ -1,5 +1,4 @@
-import type { FormEncType, FormMethod, SubmitOptions } from "@remix-run/react";
-import { useActionData, useSubmit } from "@remix-run/react";
+import { useActionData, useSubmit, type SubmitOptions } from "@remix-run/react";
import { useCallback, useEffect, useRef, useState } from "react";
const initialSubmission: {
@@ -35,14 +34,8 @@ export const useSerialSubmit = () => {
}
}, [actionData, submission, submit]);
- return useCallback((form: HTMLFormElement) => {
- const formData = new FormData(form);
+ return useCallback((formData: FormData, options: SubmitOptions) => {
const data = Array.from(formData.entries());
- const options = {
- method: form.method as FormMethod,
- action: form.action,
- encType: form.enctype as FormEncType,
- };
setSubmission({ data, options });
}, []);
};
diff --git a/packages/asset-uploader/src/index.ts b/packages/asset-uploader/src/index.ts
index 5a86ad4cc6..83cf8c43dd 100644
--- a/packages/asset-uploader/src/index.ts
+++ b/packages/asset-uploader/src/index.ts
@@ -1,3 +1,4 @@
export * from "./types";
export * from "./constants";
export * from "./utils/filter-by-type";
+export * from "./utils/to-bytes";
diff --git a/packages/asset-uploader/src/schema.ts b/packages/asset-uploader/src/schema.ts
index 0bba6f7173..a723602c71 100644
--- a/packages/asset-uploader/src/schema.ts
+++ b/packages/asset-uploader/src/schema.ts
@@ -1,7 +1,14 @@
import { z } from "zod";
-import { DEFAULT_UPLOAD_PATH } from "./constants";
+import { DEFAULT_UPLOAD_PATH, MAX_UPLOAD_SIZE } from "./constants";
+import { toBytes } from "./utils/to-bytes";
-export const S3EnvVariables = z.object({
+const maxSize = z
+ .string()
+ // user inputs the max value in mb and we transform it to bytes
+ .transform(toBytes)
+ .default(MAX_UPLOAD_SIZE);
+
+export const S3Env = z.object({
S3_ENDPOINT: z.string(),
S3_REGION: z.string(),
S3_ACCESS_KEY_ID: z.string(),
@@ -9,8 +16,10 @@ export const S3EnvVariables = z.object({
S3_BUCKET: z.string(),
S3_ACL: z.string().optional(),
ASSET_CDN_URL: z.string().optional(),
+ MAX_UPLOAD_SIZE: maxSize,
});
-export const FsEnvVariables = z.object({
- FILE_UPLOAD_PATH: z.string().optional().default(DEFAULT_UPLOAD_PATH),
+export const FsEnv = z.object({
+ MAX_UPLOAD_SIZE: maxSize,
+ FILE_UPLOAD_PATH: z.string().default(DEFAULT_UPLOAD_PATH),
});
diff --git a/packages/asset-uploader/src/targets/fs/file-path.ts b/packages/asset-uploader/src/targets/fs/file-path.ts
index 9f3020fb37..60a0215dde 100644
--- a/packages/asset-uploader/src/targets/fs/file-path.ts
+++ b/packages/asset-uploader/src/targets/fs/file-path.ts
@@ -1,15 +1,10 @@
import path from "path";
import appRoot from "app-root-path";
-import { FsEnvVariables } from "../../schema";
-const fsUploadVars = FsEnvVariables.parse(process.env);
+import { FsEnv } from "../../schema";
+const fsEnv = FsEnv.parse(process.env);
export const FILE_DIRECTORY =
// @todo this will be wrong once we have a local app that is in production and yet saves to local dir
process.env.NODE_ENV === "production"
- ? path.join(appRoot.path, fsUploadVars.FILE_UPLOAD_PATH)
- : path.join(
- appRoot.path,
- "apps",
- "designer",
- fsUploadVars.FILE_UPLOAD_PATH
- );
+ ? path.join(appRoot.path, fsEnv.FILE_UPLOAD_PATH)
+ : path.join(appRoot.path, "apps", "designer", fsEnv.FILE_UPLOAD_PATH);
diff --git a/packages/asset-uploader/src/targets/s3/client.ts b/packages/asset-uploader/src/targets/s3/client.ts
index 2393917be8..1d0114519d 100644
--- a/packages/asset-uploader/src/targets/s3/client.ts
+++ b/packages/asset-uploader/src/targets/s3/client.ts
@@ -1,14 +1,14 @@
import { S3Client } from "@aws-sdk/client-s3";
-import { S3EnvVariables } from "../../schema";
+import { S3Env } from "../../schema";
export const getS3Client = () => {
- const s3Envs = S3EnvVariables.parse(process.env);
+ const s3Env = S3Env.parse(process.env);
return new S3Client({
- endpoint: s3Envs.S3_ENDPOINT,
- region: s3Envs.S3_REGION,
+ endpoint: s3Env.S3_ENDPOINT,
+ region: s3Env.S3_REGION,
credentials: {
- accessKeyId: s3Envs.S3_ACCESS_KEY_ID,
- secretAccessKey: s3Envs.S3_SECRET_ACCESS_KEY,
+ accessKeyId: s3Env.S3_ACCESS_KEY_ID,
+ secretAccessKey: s3Env.S3_SECRET_ACCESS_KEY,
},
});
};
diff --git a/packages/asset-uploader/src/targets/s3/delete.ts b/packages/asset-uploader/src/targets/s3/delete.ts
index 90b4eb019b..79988370eb 100644
--- a/packages/asset-uploader/src/targets/s3/delete.ts
+++ b/packages/asset-uploader/src/targets/s3/delete.ts
@@ -1,12 +1,12 @@
import { DeleteObjectCommand } from "@aws-sdk/client-s3";
-import { S3EnvVariables } from "../../schema";
+import { S3Env } from "../../schema";
import { getS3Client } from "../../targets/s3/client";
export const deleteFromS3 = async (name: string) => {
- const s3Envs = S3EnvVariables.parse(process.env);
+ const s3Env = S3Env.parse(process.env);
await getS3Client().send(
new DeleteObjectCommand({
- Bucket: s3Envs.S3_BUCKET,
+ Bucket: s3Env.S3_BUCKET,
Key: name,
})
);
diff --git a/packages/asset-uploader/src/targets/s3/upload.ts b/packages/asset-uploader/src/targets/s3/upload.ts
index 4a1cc69e70..d4e4c8032e 100644
--- a/packages/asset-uploader/src/targets/s3/upload.ts
+++ b/packages/asset-uploader/src/targets/s3/upload.ts
@@ -2,11 +2,12 @@ import { z } from "zod";
import {
type UploadHandlerPart,
unstable_parseMultipartFormData,
+ MaxPartSizeExceededError,
} from "@remix-run/node";
import { PutObjectCommandInput } from "@aws-sdk/client-s3";
import { Upload } from "@aws-sdk/lib-storage";
import { Location } from "@webstudio-is/prisma-client";
-import { S3EnvVariables } from "../../schema";
+import { S3Env } from "../../schema";
import { toUint8Array } from "../../utils/to-uint8-array";
import { getAssetData } from "../../utils/get-asset-data";
import { createMany } from "../../db";
@@ -64,7 +65,7 @@ const uploadHandler = async ({
const data = await toUint8Array(file.data);
if (data.byteLength > maxSize) {
- throw new Error(`Asset cannot be bigger than ${maxSize}MB`);
+ throw new MaxPartSizeExceededError(file.name, maxSize);
}
if (file.filename === undefined) {
@@ -73,14 +74,14 @@ const uploadHandler = async ({
const uniqueFilename = getUniqueFilename(file.filename);
- const s3Envs = S3EnvVariables.parse(process.env);
+ const s3Env = S3Env.parse(process.env);
// if there is no ACL passed we do not default since some providers do not support it
- const ACL = s3Envs.S3_ACL ? { ACL: s3Envs.S3_ACL } : {};
+ const ACL = s3Env.S3_ACL ? { ACL: s3Env.S3_ACL } : {};
const params: PutObjectCommandInput = {
...ACL,
- Bucket: s3Envs.S3_BUCKET,
+ Bucket: s3Env.S3_BUCKET,
Key: encodeURIComponent(uniqueFilename),
Body: data,
ContentType: file.contentType,
diff --git a/packages/asset-uploader/src/upload.ts b/packages/asset-uploader/src/upload.ts
index c73f1fd47d..d7721c0132 100644
--- a/packages/asset-uploader/src/upload.ts
+++ b/packages/asset-uploader/src/upload.ts
@@ -1,18 +1,9 @@
-import { z } from "zod";
-import { MAX_UPLOAD_SIZE } from "./constants";
-import { S3EnvVariables } from "./schema";
+import { S3Env, FsEnv } from "./schema";
import { uploadToFs } from "./targets/fs/upload";
import { uploadToS3 } from "./targets/s3/upload";
-const AssetEnvVariables = z.object({
- MAX_UPLOAD_SIZE: z.string().optional().default(MAX_UPLOAD_SIZE),
-});
-
-const isS3Upload = S3EnvVariables.safeParse(process.env).success;
-const commonUploadVars = AssetEnvVariables.parse(process.env);
-
-// user inputs the max value in mb and we transform it to bytes
-const maxSize = parseFloat(commonUploadVars.MAX_UPLOAD_SIZE) * 1e6;
+const isS3Upload = S3Env.safeParse(process.env).success;
+const fsEnv = FsEnv.parse(process.env);
export const uploadAssets = async ({
request,
@@ -21,17 +12,16 @@ export const uploadAssets = async ({
request: Request;
projectId: string;
}) => {
- try {
- if (isS3Upload) {
- return await uploadToS3({ request, projectId, maxSize });
- }
- return await uploadToFs({ request, projectId, maxSize });
- } catch (error) {
- if (error instanceof Error && "maxBytes" in error) {
- throw new Error(
- `Asset cannot be bigger than ${commonUploadVars.MAX_UPLOAD_SIZE}MB`
- );
- }
- throw error;
+ if (isS3Upload) {
+ return await uploadToS3({
+ request,
+ projectId,
+ maxSize: fsEnv.MAX_UPLOAD_SIZE,
+ });
}
+ return await uploadToFs({
+ request,
+ projectId,
+ maxSize: fsEnv.MAX_UPLOAD_SIZE,
+ });
};
diff --git a/packages/asset-uploader/src/utils/get-asset-path.ts b/packages/asset-uploader/src/utils/get-asset-path.ts
index 881c40dc2d..80238d5c0a 100644
--- a/packages/asset-uploader/src/utils/get-asset-path.ts
+++ b/packages/asset-uploader/src/utils/get-asset-path.ts
@@ -1,13 +1,13 @@
import { Asset as DbAsset, Location } from "@webstudio-is/prisma-client";
-import { FsEnvVariables, S3EnvVariables } from "../schema";
+import { FsEnv, S3Env } from "../schema";
import path from "path";
-const s3Envs = S3EnvVariables.safeParse(process.env);
-const fsEnvs = FsEnvVariables.parse(process.env);
+const s3Envs = S3Env.safeParse(process.env);
+const fsEnv = FsEnv.parse(process.env);
export const getAssetPath = (asset: DbAsset) => {
if (asset.location === Location.FS) {
- const splitPath = fsEnvs.FILE_UPLOAD_PATH.split("public");
+ const splitPath = fsEnv.FILE_UPLOAD_PATH.split("public");
return path.join("/", splitPath[splitPath.length - 1], asset.name);
}
diff --git a/packages/asset-uploader/src/utils/to-bytes.ts b/packages/asset-uploader/src/utils/to-bytes.ts
new file mode 100644
index 0000000000..7d187f6830
--- /dev/null
+++ b/packages/asset-uploader/src/utils/to-bytes.ts
@@ -0,0 +1,2 @@
+// Convert a string value in assumed MB to bytes number
+export const toBytes = (value: string) => parseFloat(value) * 1e6;