Skip to content

Commit

Permalink
4888 add filename field upload (#4962)
Browse files Browse the repository at this point in the history
* 4888 filename sent as part of the body during file uploads
  • Loading branch information
fnocetti authored Aug 4, 2022
1 parent 7095114 commit 999031c
Show file tree
Hide file tree
Showing 11 changed files with 55 additions and 7 deletions.
6 changes: 5 additions & 1 deletion app/api/files/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,11 @@ export default (app: Application) => {
activitylogMiddleware,
(req, res, next) => {
files
.save({ ...req.file, ...req.body, type: 'attachment' })
.save({
...req.file,
...req.body,
type: 'attachment',
})
.then(saved => {
res.json(saved);
})
Expand Down
Binary file added app/api/files/specs/Aló mundo.pdf
Binary file not shown.
Binary file added app/api/files/specs/Hello, World.pdf
Binary file not shown.
22 changes: 21 additions & 1 deletion app/api/files/specs/routes.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import request, { Response as SuperTestResponse } from 'supertest';
import { Application, Request, Response, NextFunction } from 'express';

import { search } from 'api/search';
import { fileExists } from '../storage';
import db from 'api/utils/testing_db';
import { setUpApp } from 'api/utils/testingRoutes';
import connections from 'api/relationships';
Expand All @@ -12,6 +11,8 @@ import { FileType } from 'shared/types/fileType';
import entities from 'api/entities';
import * as ocrRecords from 'api/services/ocr/ocrRecords';
import { testingEnvironment } from 'api/utils/testingEnvironment';
import { errorLog } from 'api/log';
import { fileExists } from '../storage';
import {
fixtures,
uploadId,
Expand Down Expand Up @@ -272,12 +273,31 @@ describe('files routes', () => {

describe('POST/files/upload/document', () => {
it('should save the attached file', async () => {
spyOn(errorLog, 'debug');
const response = await request(app)
.post('/api/files/upload/document')
.attach('file', path.join(__dirname, 'test.txt'));
expect(response.status).toBe(200);
const [file]: FileType[] = await files.get({ originalname: 'test.txt' });
expect(await fileExists(file.filename!, 'document')).toBe(true);
expect(errorLog.debug).toHaveBeenCalledWith(expect.stringContaining('Deprecation'));
});
});

describe('POST/files/upload/*', () => {
describe.each(['document', 'attachment'] as FileType['type'][])('when file is a %s', type => {
it.each(['Hello, World.pdf', 'Aló mundo.pdf', 'Привет, мир.pdf', '헬로월드.pdf'])(
'should accept the filename %s in a field',
async filename => {
const response = await request(app)
.post(`/api/files/upload/${type}`)
.field('filename', filename)
.attach('file', path.join(__dirname, filename));
expect(response.status).toBe(200);
const [file]: FileType[] = await files.get({ originalname: filename, type });
expect(file).not.toBe(undefined);
}
);
});
});
});
Binary file added app/api/files/specs/Привет, мир.pdf
Binary file not shown.
Binary file added app/api/files/specs/헬로월드.pdf
Binary file not shown.
19 changes: 19 additions & 0 deletions app/api/files/uploadMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import path from 'path';
import { fs, generateFileName, pathFunction, deleteFile } from 'api/files';
import { Request, Response, NextFunction } from 'express';
import multer, { StorageEngine } from 'multer';
import { errorLog } from 'api/log/errorLog';
import { tenants } from 'api/tenants';

type multerCallback = (error: Error | null, destination: string) => void;

Expand All @@ -23,6 +25,19 @@ const move = async (req: Request, filePath: pathFunction) => {
req.file.path = filePath(req.file.filename);
};

const processOriginalFileName = (req: Request) => {
if (req.body.filename) {
return req.body.filename;
}

errorLog.debug(
// eslint-disable-next-line max-len
`[${tenants.current.name}] Deprecation warning: providing the filename in the multipart header is deprecated and will stop working in the future. Include a 'filename' field in the body instead.`
);

return req.file?.originalname;
};

const singleUpload =
(filePath?: pathFunction, storage: multer.StorageEngine = defaultStorage) =>
async (req: Request, res: Response, next: NextFunction) => {
Expand All @@ -35,6 +50,10 @@ const singleUpload =
});
// req.file.filename = req.file.key;

if (req.file) {
req.file.originalname = processOriginalFileName(req);
}

if (filePath) {
await move(req, filePath);
}
Expand Down
3 changes: 2 additions & 1 deletion app/react/Attachments/actions/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ export function uploadAttachment(entity, file, storeKeys) {
.set('Accept', 'application/json')
.set('X-Requested-With', 'XMLHttpRequest')
.field('entity', entity)
.attach('file', file, file.name)
.field('filename', file.name)
.attach('file', file)
.on('progress', data => {
dispatch({ type: types.ATTACHMENT_PROGRESS, entity, progress: Math.floor(data.percent) });
})
Expand Down
3 changes: 2 additions & 1 deletion app/react/Attachments/actions/specs/actions.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ describe('Attachments actions', () => {

store.dispatch(actions.uploadAttachment('sharedId', file, { __reducerKey: 'storeKey' }));
expect(mockUpload.field).toHaveBeenCalledWith('entity', 'sharedId');
expect(mockUpload.attach).toHaveBeenCalledWith('file', file, file.name);
expect(mockUpload.field).toHaveBeenCalledWith('filename', file.name);
expect(mockUpload.attach).toHaveBeenCalledWith('file', file);

mockUpload.emit('progress', { percent: 55.1 });
mockUpload.emit('progress', { percent: 65 });
Expand Down
6 changes: 4 additions & 2 deletions app/react/Uploads/actions/specs/uploadsActions.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,8 @@ describe('uploadsActions', () => {

store.dispatch(actions.uploadDocument('abc1', file));
expect(mockUpload.field).toHaveBeenCalledWith('entity', 'abc1');
expect(mockUpload.attach).toHaveBeenCalledWith('file', file, file.name);
expect(mockUpload.field).toHaveBeenCalledWith('filename', file.name);
expect(mockUpload.attach).toHaveBeenCalledWith('file', file);

emitProgressAndResponse(mockUpload, {
text: JSON.stringify({ test: 'test' }),
Expand Down Expand Up @@ -289,7 +290,8 @@ describe('uploadsActions', () => {
const file = getMockFile();

store.dispatch(actions.uploadCustom(file)).then(() => {
expect(mockUpload.attach).toHaveBeenCalledWith('file', file, file.name);
expect(mockUpload.field).toHaveBeenCalledWith('filename', file.name);
expect(mockUpload.attach).toHaveBeenCalledWith('file', file);
expect(store.getActions()).toEqual(expectedActions);
expect(superagent.post).toHaveBeenCalledWith(`${APIURL}files/upload/custom`);
done();
Expand Down
3 changes: 2 additions & 1 deletion app/react/Uploads/actions/uploadsActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,8 @@ export function upload(docId, file, endpoint = 'files/upload/document') {
.set('Accept', 'application/json')
.set('X-Requested-With', 'XMLHttpRequest')
.field('entity', docId)
.attach('file', file, file.name)
.field('filename', file.name)
.attach('file', file)
.on('progress', data => {
dispatch({
type: types.UPLOAD_PROGRESS,
Expand Down

0 comments on commit 999031c

Please sign in to comment.