Skip to content

Build your personal knowledge base with Trilium Notes

feat(import/markdown): properly support attachments

Elian Doran06a5f9539962
diff --git a/apps/server/src/services/import/zip.ts b/apps/server/src/services/import/zip.ts
index 0d759f6fb4..1e57773c89 100644
--- a/apps/server/src/services/import/zip.ts
+++ b/apps/server/src/services/import/zip.ts
@@ -23,6 +23,7 @@ import type TaskContext from "../task_context.js";
import treeService from "../tree.js";
import markdownService from "./markdown.js";
import mimeService from "./mime.js";
+import { isMarkdownCodeNote } from "../export/rewrite_links.js";
interface MetaFile {
files: NoteMeta[];
@@ -406,6 +407,10 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Bu
content = processTextNoteContent(content, noteTitle, filePath, noteMeta);
}
+ if (type === "code" && isMarkdownCodeNote(mime) && typeof content === "string") {
+ content = processMarkdownCodeNoteContent(content, filePath);
+ }
+
if (type === "relationMap" && noteMeta && typeof content === "string") {
const relationMapLinks = (noteMeta.attributes || []).filter((attr) => attr.type === "relation" && attr.name === "relationMapLink");
@@ -419,6 +424,62 @@ async function importZip(taskContext: TaskContext<"importNotes">, fileBuffer: Bu
return content;
}
+ /**
+ * Rewrites relative file paths in markdown code notes back to Trilium internal
+ * URLs (counterpart to `rewriteMarkdownContentLinks` in the export).
+ */
+ function processMarkdownCodeNoteContent(content: string, filePath: string) {
+ function isUrlAbsolute(url: string) {
+ return /^(?:[a-z]+:)?\/\//i.test(url);
+ }
+
+ // Image links: ![alt](relative/path)
+ content = content.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (match, alt, url) => {
+ try {
+ url = decodeURIComponent(url).trim();
+ } catch {
+ return match;
+ }
+
+ if (isUrlAbsolute(url) || url.startsWith("api/")) {
+ return match;
+ }
+
+ const target = getEntityIdFromRelativeUrl(url, filePath);
+
+ if (target.attachmentId) {
+ return `![${alt}](api/attachments/${target.attachmentId}/image/image)`;
+ } else if (target.noteId) {
+ return `![${alt}](api/images/${target.noteId}/image)`;
+ }
+ return match;
+ });
+
+ // Non-image links: [text](relative/path)
+ content = content.replace(/(?<!!)\[([^\]]*)\]\(([^)]+)\)/g, (match, text, url) => {
+ try {
+ url = decodeURIComponent(url).trim();
+ } catch {
+ return match;
+ }
+
+ if (isUrlAbsolute(url) || url.startsWith("#") || url.startsWith("api/")) {
+ return match;
+ }
+
+ const target = getEntityIdFromRelativeUrl(url, filePath);
+
+ if (target.attachmentId) {
+ return `[${text}](#root/${target.noteId}?viewMode=attachments&attachmentId=${target.attachmentId})`;
+ } else if (target.noteId) {
+ return `[${text}](#root/${target.noteId})`;
+ }
+ return match;
+ });
+
+ return content;
+ }
+
function saveNote(filePath: string, content: string | Buffer) {
const { parentNoteMeta, noteMeta, attachmentMeta } = getMeta(filePath);