IFraim
@IFraim
Web-Developer

Nest JS — Как получить изображение из dist в браузере?

Изображения сохраняются в dist/uploads/image
603547e878583571558491.png
60354880839bc221981959.png
main.ts
import { AppModule } from './modules/app.module';
import { NestFactory } from '@nestjs/core';
import { ValidateInputPipe } from './validators/validate.pipe';

async function startServer() {
  const PORT = process.env.PORT || 5000
  const app = await NestFactory.create(AppModule);
  app.setGlobalPrefix("/api")
  app.useGlobalPipes(new ValidateInputPipe())
  app.enableCors()
  
  await app.listen(PORT);
}
startServer();


file.service.ts
import { HttpException, HttpStatus, Injectable } from "@nestjs/common";
import * as path from "path"
import * as fs from "fs"
import * as uuid from "uuid"

export enum FileType {
    IMAGE = "image",
    VIDEO = "video",
    AUDIO = "audio",
    PDF = "pdf"
}

@Injectable()
export class FileService {
    constructor() {}

    createFile(type: FileType, file): string {
        try {
            const fileExtension = file.originalname.split(".").pop()
            const fileName = uuid.v4() + "." + fileExtension

            const filePath = path.resolve(__dirname, "..", "uploads", type)
            if (!fs.existsSync(filePath)) fs.mkdirSync(filePath, {recursive: true})
            fs.writeFileSync(path.resolve(filePath, fileName), file.buffer)

            return type + "/" + fileName
        } catch (error) {
            throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR)
        }
    }
    removeFile(filename: string) {}
}


file.module.ts
import { FileService } from './../services/file.service';
import { Module } from "@nestjs/common";

@Module({
    providers: [FileService]
})
export class FileModule {}


courses.controller.ts
import { CoursesService } from './../services/courses.service';
import { Body, Controller, Delete, Get, Post, UploadedFile, UseInterceptors } from "@nestjs/common";
import { FileInterceptor } from '@nestjs/platform-express';

@Controller("/courses")
export class CoursesController {
    constructor(private coursesService: CoursesService) {}

    @Post("/create")
    @UseInterceptors(FileInterceptor("logo"))
    createCourse(@Body() dataCourse: any, @UploadedFile() logo: any) {
        return this.coursesService.create(dataCourse, logo)
    }
}
  • Вопрос задан
  • 1395 просмотров
Решения вопроса 1
Пригласить эксперта
Ответы на вопрос 1
IFraim
@IFraim Автор вопроса
Web-Developer
Я устранил эту проблему, изменив file.controller.ts и поменяв расположение папки с изображениями
import { FileService } from './../services/file.service';
import { Controller, Get, Param, Res } from "@nestjs/common";

@Controller("/files")
export class FilesController {
    constructor (private fileService: FileService) {}

    @Get("/:filename")
    async getFile(@Param("filename") filename: string, @Res() res: any) {
        res.sendFile(filename, { root: 'static/image'});
    }
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы