trilium/src/routes/api/image.js

52 lines
1.3 KiB
JavaScript
Raw Normal View History

"use strict";
const imageService = require('../../services/image');
2018-04-01 23:42:12 +08:00
const repository = require('../../services/repository');
2018-01-08 03:07:59 +08:00
const RESOURCE_DIR = require('../../services/resource_dir').RESOURCE_DIR;
const fs = require('fs');
async function returnImage(req, res) {
2018-11-08 17:30:35 +08:00
const image = await repository.getNote(req.params.noteId);
if (!image) {
return res.sendStatus(404);
}
2018-11-08 17:30:35 +08:00
else if (image.type !== 'image') {
return res.sendStatus(400);
}
2018-01-08 03:07:59 +08:00
else if (image.data === null) {
res.set('Content-Type', 'image/png');
return res.send(fs.readFileSync(RESOURCE_DIR + '/db/image-deleted.png'));
}
2018-11-08 17:30:35 +08:00
res.set('Content-Type', image.mime);
2019-02-10 21:33:13 +08:00
res.send(await image.getContent());
}
async function uploadImage(req) {
2018-01-07 10:49:02 +08:00
const noteId = req.query.noteId;
const file = req.file;
2018-04-01 23:42:12 +08:00
const note = await repository.getNote(noteId);
2018-01-07 10:49:02 +08:00
if (!note) {
return [404, `Note ${noteId} doesn't exist.`];
2018-01-07 10:49:02 +08:00
}
2018-01-07 22:22:55 +08:00
if (!["image/png", "image/jpeg", "image/gif"].includes(file.mimetype)) {
return [400, "Unknown image type: " + file.mimetype];
}
const {url} = await imageService.saveImage(file.buffer, file.originalname, noteId);
return {
uploaded: true,
url
};
}
module.exports = {
returnImage,
uploadImage
};