mirror of
https://gitlab.com/comunic/comunicapiv2
synced 2025-06-20 00:25:17 +00:00
Can compress received image
This commit is contained in:
@ -4,6 +4,8 @@ import { APIClient } from "./APIClient";
|
||||
import { checkMail } from "../utils/StringUtils";
|
||||
import { AccountHelper } from "../helpers/AccountHelper";
|
||||
import { UploadedFile } from "express-fileupload";
|
||||
import { prepareFileCreation, generateNewUserDataFileName, pathUserData } from "../utils/UserDataUtils";
|
||||
import * as sharp from 'sharp';
|
||||
|
||||
/**
|
||||
* Response to a request
|
||||
@ -175,7 +177,7 @@ export class RequestHandler {
|
||||
*
|
||||
* @param name The name of the posted file
|
||||
*/
|
||||
private GetUploadedFile(name: string) : undefined | UploadedFile {
|
||||
private getUploadedFile(name: string) : undefined | UploadedFile {
|
||||
|
||||
if(!this.req.files)
|
||||
return undefined;
|
||||
@ -192,9 +194,42 @@ export class RequestHandler {
|
||||
* @param name The name of the file to check
|
||||
*/
|
||||
public hasFile(name: string) : boolean {
|
||||
return this.GetUploadedFile(name) != undefined;
|
||||
return this.getUploadedFile(name) != undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save an image in user data directory
|
||||
*
|
||||
* @param postField The name of the POST field
|
||||
* @param folder Target folder in user data directory
|
||||
* @param maxW Maximum width of the image
|
||||
* @param maxH Maximum height of the image
|
||||
*/
|
||||
public async savePostImage(postField: string, folder: string, maxW: number, maxH: number) : Promise<string> {
|
||||
const file = this.getUploadedFile(postField);
|
||||
if(file == undefined)
|
||||
this.error(400, "File '"+postField+"' is missing in the request !");
|
||||
|
||||
const targetUserDataFolder = prepareFileCreation(this.getUserId(), folder);
|
||||
const targetFilePath = generateNewUserDataFileName(targetUserDataFolder, "png");
|
||||
const targetSysPath = pathUserData(targetFilePath, true);
|
||||
|
||||
// Process image size
|
||||
let img = sharp(file.data);
|
||||
const stats = await img.metadata();
|
||||
if(stats.width > maxW || stats.height > maxH) {
|
||||
if(stats.width > maxW)
|
||||
img = img.resize(maxW, Math.floor((stats.height*maxW)/stats.width));
|
||||
else
|
||||
img = img.resize(Math.floor((stats.width*maxH)/stats.height), maxH);
|
||||
}
|
||||
|
||||
// Save image
|
||||
await img.png().toFile(targetSysPath);
|
||||
|
||||
|
||||
return targetFilePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate API tokens
|
||||
|
Reference in New Issue
Block a user