Download attachments with original filenames

This commit is contained in:
Denis
2024-07-30 23:48:15 +03:00
parent 305ce29ebb
commit 832cdacebf
3 changed files with 23 additions and 6 deletions

View File

@@ -250,10 +250,12 @@ export class AttachmentsController extends BaseController {
res: Response,
next: NextFunction
): Promise<Response | void> {
const { tenantId } = req;
const { id: documentKey } = req.params;
try {
const presignedUrl = await this.attachmentsApplication.getPresignedUrl(
tenantId,
documentKey
);
return res.status(200).send({ presignedUrl });

View File

@@ -96,10 +96,11 @@ export class AttachmentsApplication {
/**
* Retrieves the presigned url of the given attachment key.
* @param {number} tenantId
* @param {string} key
* @returns {Promise<string>}
*/
public getPresignedUrl(key: string): Promise<string> {
return this.getPresignedUrlService.getPresignedUrl(key);
public getPresignedUrl(tenantId: number, key: string): Promise<string> {
return this.getPresignedUrlService.getPresignedUrl(tenantId, key);
}
}

View File

@@ -1,20 +1,34 @@
import { Service } from 'typedi';
import { Inject, Service } from 'typedi';
import { GetObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { s3 } from '@/lib/S3/S3';
import config from '@/config';
import HasTenancyService from '../Tenancy/TenancyService';
@Service()
export class getAttachmentPresignedUrl {
@Inject()
private tenancy: HasTenancyService;
/**
* Retrieves the presigned url of the given attachment key.
* Retrieves the presigned url of the given attachment key with the original filename.
* @param {number} tenantId
* @param {string} key
* @returns {Promise<string?>}
* @returns {string}
*/
async getPresignedUrl(key: string) {
async getPresignedUrl(tenantId: number, key: string) {
const { Document } = this.tenancy.models(tenantId);
const foundDocument = await Document.query().findOne({ key });
let ResponseContentDisposition = 'attachment';
if (foundDocument && foundDocument.originName) {
ResponseContentDisposition += `; filename="${foundDocument.originName}"`;
}
const command = new GetObjectCommand({
Bucket: config.s3.bucket,
Key: key,
ResponseContentDisposition,
});
const signedUrl = await getSignedUrl(s3, command, { expiresIn: 300 });