Hi there! First of all, I'd like to point out that I started my first job as a dev 4 months ago, and I was mostly (about 90%) frontend. I did some backend projects, but nothing massive. So this is me asking from a 2 month ish learning standpoint. Now:
At work, I was asked to create a file upload system that writes to disk, and then serves files. These files are stored in the computer where our nest js server is running, it works fine, and I haven't noticed failed uploads, or problems with images/uploads, which is great. I've been using the UseInterceptors decorator with FileInterceptors, and on the logic for it, I am writing to disk.
Then, on the service, I'm wrapping my db calls a try catch block since, if anything fails, I want to unlink/delete the files since I can't put the file interceptor logic in a prisma transaction. This is my code:
@UseInterceptors(
FileInterceptor('expenses', {
storage: diskStorage({
destination: (req, file, cb) => {
const folderPath = getUploadDestination(file.fieldname); // 'expenses'
cb(null, folderPath);
},
filename: (req, file, cb) => {
const uniqueName = getFileName(file.originalname);
cb(null, uniqueName);
},
}),
limits: {
fileSize: MAX_SIZE_IN_BYTES,
},
fileFilter: (req, file, cb) => {
const accept = /image\/(jpeg|png)/;
if (!accept.test(file.mimetype)) {
return cb(
new BadRequestException(
`Invalid signature file type: ${file.mimetype}. Only images are allowed.`,
),
false,
);
}
cb(null, true);
},
}),
)
Will post the service below due to limitations.