Я понятия не имею, как сделать следующее:
У меня есть этот маршрут: "localhost: 3000 / t-клиентов / {id} / t-consents"
Что он делает : Сохранение пути для изображения, которое также должно быть загружено в путь. Таблица в базе данных выглядит следующим образом:
Итак, по идентификатору клиента я хочу загрузить картинку на стороне сервера. У меня есть контроллер, который загружает изображение и тот, который выполняет маршрут, показанный выше. Что я хочу сделать, это вызвать контроллер, который загружает файл в мой контроллер, который обрабатывает маршрут. Я понятия не имею, как это сделать.
Вот мои два контроллера, о которых я говорил:
import {inject} from '@loopback/context';
import {
post,
Request,
requestBody,
Response,
RestBindings,
} from '@loopback/rest';
import {FILE_UPLOAD_SERVICE} from '../keys';
import {FileUploadHandler} from '../types';
/**
* A controller to handle file uploads using multipart/form-data media type
*/
export class FileUploadController {
/**
* Constructor
* @param handler - Inject an express request handler to deal with the request
*/
constructor(
@inject(FILE_UPLOAD_SERVICE) private handler: FileUploadHandler,
) {}
@post('/file-upload', {
responses: {
200: {
content: {
'application/json': {
schema: {
type: 'object',
},
},
},
description: 'Files and fields',
},
},
})
async fileUpload(
@requestBody({
description: 'multipart/form-data for files/fields',
required: true,
content: {
'multipart/form-data': {
// Skip body parsing
'x-parser': 'stream',
schema: {
type: 'object',
properties: {
file: {type: 'string', format: 'binary'},
},
},
},
},
})
request: Request,
@inject(RestBindings.Http.RESPONSE) response: Response,
): Promise<object> {
return new Promise<object>((resolve, reject) => {
this.handler(request, response, (err: any) => {
if (err) {
reject(err);
} else {
resolve(FileUploadController.getFilesAndFields(request));
}
});
});
}
/**
* Get files and fields for the request
* @param request - Http request
*/
private static getFilesAndFields(request: Request) {
const uploadedFiles = request.files;
const mapper = (f: globalThis.Express.Multer.File) => ({
fieldname: f.fieldname,
originalname: f.originalname,
encoding: f.encoding,
mimetype: f.mimetype,
size: f.size,
});
let files: object[] = [];
//If only 1 file
if (Array.isArray(uploadedFiles)) {
files = uploadedFiles.map(mapper);
} else {
//if more than 1
for (const filename in uploadedFiles) {
files.push(...uploadedFiles[filename].map(mapper));
}
}
return {files, fields: request.body};
}
}
Другой
import {
Count,
CountSchema,
Filter,
repository,
Where,
} from '@loopback/repository';
import {
del,
get,
getModelSchemaRef,
getWhereSchemaFor,
param,
patch,
post,
requestBody,
} from '@loopback/rest';
import {TClient, TConsent} from '../models';
import {TClientRepository} from '../repositories';
export class TClientTConsentController {
constructor(
@repository(TClientRepository)
protected tClientRepository: TClientRepository,
) {}
@get('/t-clients/{id}/t-consents', {
responses: {
'200': {
description: 'Array of TClient has many TConsent',
content: {
'application/json': {
schema: {type: 'array', items: getModelSchemaRef(TConsent)},
},
},
},
},
})
async find(
@param.path.number('id') id: number,
@param.query.object('filter') filter?: Filter<TConsent>,
): Promise<TConsent[]> {
return this.tClientRepository.clicon(id).find(filter);
}
@post('/t-clients/{id}/t-consents', {
responses: {
'200': {
description: 'TClient model instance',
content: {'application/json': {schema: getModelSchemaRef(TConsent)}},
},
},
})
async create(
@param.path.number('id') id: typeof TClient.prototype.idClient,
@requestBody({
content: {
'application/json': {
schema: getModelSchemaRef(TConsent, {
title: 'NewTConsentInTClient',
exclude: ['idConsent', 'fkClient'],
//optional: ['fkClient']
}),
},
},
})
tConsent: Omit<TConsent, 'idConsent'>,
): Promise<TConsent> {
return this.tClientRepository.clicon(id).create(tConsent);
}
@patch('/t-clients/{id}/t-consents', {
responses: {
'200': {
description: 'TClient.TConsent PATCH success count',
content: {'application/json': {schema: CountSchema}},
},
},
})
async patch(
@param.path.number('id') id: number,
@requestBody({
content: {
'application/json': {
schema: getModelSchemaRef(TConsent, {partial: true}),
},
},
})
tConsent: Partial<TConsent>,
@param.query.object('where', getWhereSchemaFor(TConsent))
where?: Where<TConsent>,
): Promise<Count> {
return this.tClientRepository.clicon(id).patch(tConsent, where);
}
@del('/t-clients/{id}/t-consents', {
responses: {
'200': {
description: 'TClient.TConsent DELETE success count',
content: {'application/json': {schema: CountSchema}},
},
},
})
async delete(
@param.path.number('id') id: number,
@param.query.object('where', getWhereSchemaFor(TConsent))
where?: Where<TConsent>,
): Promise<Count> {
return this.tClientRepository.clicon(id).delete(where);
}
}
Итак, моя цель - загрузить файл на маршрут, Маршрут получает сообщение с файлом и, возможно, некоторым текстом, например, именем файла, и контроллер сохраняет изображение и устанавливает «conPath» для пути к файлу в каталоге сервера.
Спасибо за чтение. Я доступен для любых деталей.