53 lines
2 KiB
TypeScript
53 lines
2 KiB
TypeScript
import { Controller, Get } from "@overnightjs/core";
|
|
import { File } from "../models/init-models.js";
|
|
import { StatusCodes } from "http-status-codes";
|
|
import { Request, Response } from "express";
|
|
import * as path from "path";
|
|
import * as fs from "fs";
|
|
|
|
@Controller("file")
|
|
export class FileController {
|
|
// constructor() {}
|
|
|
|
@Get("download/:id")
|
|
public async findOne(req: Request, res: Response) {
|
|
const id = req.params.id;
|
|
const file = await File.findOne({
|
|
where: { id: id },
|
|
});
|
|
if (file) {
|
|
const filePath = "/storage/app/public/" + file.path_name;
|
|
const ext = path.extname(filePath);
|
|
const fileName = file.label + ext;
|
|
try {
|
|
fs.accessSync(filePath, fs.constants.R_OK | fs.constants.W_OK);
|
|
// console.log("can read/write:", path);
|
|
res.set({
|
|
"Cache-Control": "no-cache private",
|
|
"Content-Description": "File Transfer",
|
|
"Content-Type": file.mime_type,
|
|
"Content-Disposition": "inline; filename=" + fileName,
|
|
"Content-Transfer-Encoding": "binary",
|
|
});
|
|
res.status(StatusCodes.OK).sendFile(filePath);
|
|
} catch (err) {
|
|
// console.log("no access:", path);
|
|
res.status(StatusCodes.NOT_FOUND).send({
|
|
message: `File with id ${id} doesn't exist on file server`,
|
|
});
|
|
}
|
|
|
|
// res.status(StatusCodes.OK).sendFile(filePath, (err) => {
|
|
// // res.setHeader("Content-Type", "application/json");
|
|
// // res.removeHeader("Content-Disposition");
|
|
// res.status(StatusCodes.NOT_FOUND).send({
|
|
// message: `File with id ${id} doesn't exist on file server`,
|
|
// });
|
|
// });
|
|
} else {
|
|
res.status(StatusCodes.NOT_FOUND).send({
|
|
message: `Cannot find File with id=${id}.`,
|
|
});
|
|
}
|
|
}
|
|
}
|