trilium/src/routes/api/file_upload.js

68 lines
2 KiB
JavaScript
Raw Normal View History

2018-02-15 12:31:20 +08:00
"use strict";
const noteService = require('../../services/notes');
const protectedSessionService = require('../../services/protected_session');
2018-04-01 23:42:12 +08:00
const repository = require('../../services/repository');
const utils = require('../../services/utils');
2018-02-15 12:31:20 +08:00
async function uploadFile(req) {
2018-02-15 12:31:20 +08:00
const parentNoteId = req.params.parentNoteId;
const file = req.file;
const originalName = file.originalname;
const size = file.size;
const mime = file.mimetype.toLowerCase();
2018-02-15 12:31:20 +08:00
2018-04-01 23:42:12 +08:00
const parentNote = await repository.getNote(parentNoteId);
2018-02-15 12:31:20 +08:00
2018-04-01 23:42:12 +08:00
if (!parentNote) {
return [404, `Note ${parentNoteId} doesn't exist.`];
2018-02-15 12:31:20 +08:00
}
const {note} = await noteService.createNote(parentNoteId, originalName, file.buffer, {
target: 'into',
isProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable(),
type: mime.startsWith("image/") ? 'image' : 'file',
mime: file.mimetype,
attributes: [
{ type: "label", name: "originalFileName", value: originalName },
{ type: "label", name: "fileSize", value: size }
]
2018-04-01 23:42:12 +08:00
});
return {
2018-04-01 23:42:12 +08:00
noteId: note.noteId
};
}
2019-01-27 22:47:40 +08:00
async function downloadNoteFile(noteId, res) {
2018-04-01 23:42:12 +08:00
const note = await repository.getNote(noteId);
if (!note) {
return res.status(404).send(`Note ${noteId} doesn't exist.`);
}
if (note.isProtected && !protectedSessionService.isProtectedSessionAvailable()) {
2019-01-27 22:47:40 +08:00
return res.status(401).send("Protected session not available");
}
const originalFileName = await note.getLabel('originalFileName');
2018-11-05 07:06:17 +08:00
const fileName = originalFileName ? originalFileName.value : note.title;
res.setHeader('Content-Disposition', utils.getContentDisposition(fileName));
res.setHeader('Content-Type', note.mime);
res.send(note.content);
}
2019-01-27 22:47:40 +08:00
async function downloadFile(req, res) {
const noteId = req.params.noteId;
return await downloadNoteFile(noteId, res);
}
module.exports = {
uploadFile,
2019-01-27 22:47:40 +08:00
downloadFile,
downloadNoteFile
};