Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat: add mobile attachment upload

tianma779784de15e7
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 7ac56c18..c41c6561 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -194,6 +194,7 @@ const SESSION_TOKEN_BYTES = 32;
const DEFAULT_SESSION_TTL_DAYS = 30;
const DEFAULT_R2_BUCKET_NAME = "edgeever-resources";
const MAX_IMAGE_UPLOAD_BYTES = 50 * 1024 * 1024;
+const MAX_ATTACHMENT_UPLOAD_BYTES = 50 * 1024 * 1024;
const MAX_COMPRESSED_IMAGE_EDGE = 2560;
const IMAGE_COMPRESSION_QUALITY = 82;
const COMPRESSED_IMAGE_MIME_TYPE = "image/webp";
@@ -938,17 +939,26 @@ app.post("/api/v1/memos/:id/resources", async (c) => {
const actor = getAuditActor(c);
const bytes = new Uint8Array(await file.arrayBuffer());
+ const mimeType = file.type || "application/octet-stream";
let resource: Resource;
try {
- resource = await createImageResource(c, {
- memoId,
- filename: file.name,
- mimeType: file.type || "application/octet-stream",
- bytes,
- actor,
- source: "upload",
- });
+ resource = SUPPORTED_IMAGE_MIME_TYPES.has(mimeType)
+ ? await createImageResource(c, {
+ memoId,
+ filename: file.name,
+ mimeType,
+ bytes,
+ actor,
+ source: "upload",
+ })
+ : await createAttachmentResource(c, {
+ memoId,
+ filename: file.name,
+ mimeType,
+ bytes,
+ actor,
+ });
} catch (error) {
if (error instanceof AppError) {
return apiError(c, error.code, error.message, error.status);
@@ -1041,6 +1051,77 @@ const createImageResource = async (
return mapResource(resource);
};
+const createAttachmentResource = async (
+ c: AppContext,
+ input: {
+ memoId: string;
+ filename: string;
+ mimeType: string;
+ bytes: Uint8Array;
+ actor: AuditActor;
+ }
+) => {
+ validateAttachmentUpload(input.bytes.byteLength);
+
+ const resourceId = createId("res");
+ const now = isoNow();
+ const filename = normalizeFilename(input.filename) || resourceId;
+ const objectKey = `memos/${input.memoId}/${resourceId}`;
+ const bucketName = c.env.EDGE_EVER_R2_BUCKET_NAME?.trim() || DEFAULT_R2_BUCKET_NAME;
+ const checksum = await sha256Bytes(input.bytes);
+
+ await c.env.RESOURCES.put(objectKey, input.bytes, {
+ httpMetadata: {
+ contentType: input.mimeType,
+ cacheControl: "private, max-age=3600",
+ },
+ customMetadata: {
+ memoId: input.memoId,
+ resourceId,
+ filename,
+ },
+ });
+
+ try {
+ await c.env.DB.batch([
+ c.env.DB.prepare(
+ `INSERT INTO resources (
+ id, memo_id, bucket_name, object_key, kind, mime_type, filename,
+ byte_size, sha256, width, height, metadata_json, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, 'attachment', ?, ?, ?, ?, NULL, NULL, ?, ?, ?)`
+ ).bind(
+ resourceId,
+ input.memoId,
+ bucketName,
+ objectKey,
+ input.mimeType,
+ filename,
+ input.bytes.byteLength,
+ checksum,
+ JSON.stringify({ originalFilename: filename }),
+ now,
+ now
+ ),
+ auditStatement(c.env.DB, input.actor.actorType, input.actor.actorId, "resource.create", "resource", resourceId, {
+ memoId: input.memoId,
+ mimeType: input.mimeType,
+ byteSize: input.bytes.byteLength,
+ }),
+ ]);
+ } catch (error) {
+ await c.env.RESOURCES.delete(objectKey);
+ throw error;
+ }
+
+ const resource = await getResourceRow(c.env.DB, resourceId);
+
+ if (!resource) {
+ throw new AppError("not_found", "Resource not found", 404);
+ }
+
+ return mapResource(resource);
+};
+
const validateImageUpload = (mimeType: string, size: number) => {
if (!SUPPORTED_IMAGE_MIME_TYPES.has(mimeType)) {
throw new AppError("unsupported_media_type", "Only PNG, JPEG, GIF, WebP and AVIF images are supported.", 415);
@@ -1051,6 +1132,12 @@ const validateImageUpload = (mimeType: string, size: number) => {
}
};
+const validateAttachmentUpload = (size: number) => {
+ if (size <= 0 || size > MAX_ATTACHMENT_UPLOAD_BYTES) {
+ throw new AppError("upload_too_large", "Attachment must be between 1 byte and 50 MB.", 413);
+ }
+};
+
type PreparedImage = {
bytes: Uint8Array;
mimeType: string;
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index a22cca90..e259e5ad 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -15,6 +15,7 @@ import {
Save,
ReplaceAll,
MoreHorizontal,
+ Paperclip,
Pencil,
Sparkles,
Search,
@@ -283,6 +284,7 @@ export const EditorPane = ({
const memoRef = useRef<MemoDetail | null>(memo);
const editorRef = useRef<Editor | null>(null);
+ const fileInputRef = useRef<HTMLInputElement | null>(null);
const noteSearchInputRef = useRef<HTMLInputElement | null>(null);
const noteReplaceInputRef = useRef<HTMLInputElement | null>(null);
const hydratingRef = useRef(false);
@@ -358,6 +360,65 @@ export const EditorPane = ({
})();
}, [queryClient]);
+ const insertResourceFiles = useCallback((files: File[]) => {
+ const currentMemo = memoRef.current;
+ const currentEditor = editorRef.current;
+
+ if (!currentMemo || currentMemo.isDeleted || !currentEditor || !currentEditor.isEditable || files.length === 0) {
+ return;
+ }
+
+ const targetMemoId = currentMemo.id;
+
+ void (async () => {
+ setImageUploadState("uploading");
+
+ try {
+ for (const file of files) {
+ const isImage = SUPPORTED_PASTE_IMAGE_TYPES.has(file.type);
+ const shouldCompress = isImage && imageCompressionEnabledRef.current;
+ setImageUploadState(shouldCompress ? "compressing" : "uploading");
+ const uploadFile = shouldCompress ? (await compressImageForUpload(file)).file : file;
+
+ setImageUploadState("uploading");
+ const { resource } = await api.uploadMemoResource(targetMemoId, uploadFile);
+ void queryClient.invalidateQueries({ queryKey: ["resources"] });
+
+ if (memoRef.current?.id !== targetMemoId || !editorRef.current) {
+ setImageUploadState("idle");
+ return;
+ }
+
+ if (resource.kind === "image") {
+ editorRef.current
+ .chain()
+ .focus()
+ .setImage({
+ src: resource.url,
+ alt: file.name,
+ title: file.name,
+ })
+ .run();
+ } else {
+ editorRef.current
+ .chain()
+ .focus()
+ .insertContent({
+ type: "paragraph",
+ content: [{ type: "text", text: `附件:${resource.filename || file.name} ${resource.url}` }],
+ })
+ .run();
+ }
+ }
+
+ setImageUploadState("idle");
+ } catch {
+ setImageUploadState("error");
+ window.setTimeout(() => setImageUploadState("idle"), 2200);
+ }
+ })();
+ }, [queryClient]);
+
const editor = useEditor({
extensions: [
StarterKit,
@@ -816,7 +877,7 @@ export const EditorPane = ({
const imageUploadLabel =
imageUploadState === "error"
- ? "图片失败"
+ ? "上传失败"
: imageUploadState === "compressing"
? "压缩中"
: imageUploadState === "uploading"
@@ -977,10 +1038,10 @@ export const EditorPane = ({
)}
>
{imageUploadState === "error"
- ? "图片上传失败"
+ ? "文件上传失败"
: imageUploadState === "compressing"
? "图片压缩中"
- : "图片上传中"}
+ : "文件上传中"}
</span>
)}
<span className={cn("hidden rounded-md px-2 py-1 text-xs font-medium sm:inline-flex", saveStateClassName)}>
@@ -999,6 +1060,30 @@ export const EditorPane = ({
{saveMutation.isPending ? "保存中" : "完成"}
</button>
)}
+ <input
+ ref={fileInputRef}
+ className="hidden"
+ type="file"
+ multiple
+ onChange={(event) => {
+ const files = Array.from(event.target.files ?? []);
+ event.target.value = "";
+ insertResourceFiles(files);
+ }}
+ />
+ {isMobileEditing && !readOnly && (
+ <Button
+ className="sm:hidden"
+ size="icon"
+ variant="ghost"
+ title="上传附件"
+ aria-label="上传附件"
+ disabled={mobileDoneDisabled || effectiveReadOnly}
+ onClick={() => fileInputRef.current?.click()}
+ >
+ <Paperclip className="h-4 w-4" />
+ </Button>
+ )}
<Button className="hidden sm:inline-flex" size="icon" variant="ghost" title="搜索当前笔记" aria-label="搜索当前笔记" onClick={() => openNoteSearch()}>
<Search className="h-4 w-4" />
</Button>