【发布时间】:2022-08-12 01:35:50
【问题描述】:
我正在尝试将图像从 Angular 端上传到 NestJs。其实这是我上传的一本书。我上传了带有描述和图片的书。现在我可以上传图片,并且可以将图片路径存储为参考书。现在的情况是,当我从 Angular 端上传一本书时,它使用 imagepath 发布这本书,并且图像也存储在 NestJs 文件夹中,但我无法显示带有它的图像的书。这本书在前端显示,但没有在后端引用和保存的图像。所以请告诉我如何显示图像,这将是一个巨大的问题。
Anguar 前端代码 .ts
export class BooksComponent implements OnInit {
BookForm = new FormGroup({
_id: new FormControl(\'\'),
name: new FormControl(\'\'),
author: new FormControl(\'\'),
price: new FormControl(\'\'),
genres_name: new FormControl(\'\'),
coverimage: new FormControl(\'\'),
});
results?: Book[] = [];
searchedText: string = \'\';
constructor(
private readonly apiService: ApiService,
private router: Router
) {}
ngOnInit() {
this.apiService.getallbooks().subscribe((data) => {
this.results = data;
console.log(this.results);
});
}
我将图像存储在 \"./assets\" 文件夹中的 NestJs 后端代码。我什至尝试对图像发出@Get 请求,但没有帮助。
@ApiTags(\'Book Cover Images\')
@Controller(\'images\')
export class ImagesController {
static imageUrl: string;
constructor(private readonly bookservice: BooksService) {}
@Post(\'upload\')
@UseInterceptors(
FileInterceptor(\'file\', {
storage: diskStorage({
destination: \'./assets/\',
filename: (req, file, cb) => {
const filename: string = Array(10)
.fill(null)
.map(() => Math.round(Math.random() * 16).toString(16))
.join(\'\');
return cb(null, `${filename}${extname(file.originalname)}`);
},
}),
}),
)
async uploadFile(@UploadedFile() file: Express.Multer.File, @Request() req) {
console.log(file);
return this.imageUrl(file);
}
private imageUrl(file: Express.Multer.File) {
ImagesController.imageUrl = `./assets/${file.originalname}`;
return ImagesController.imageUrl;
}
// @Get(\'bookimages/:imagename\')
// findbookimages(
// @Param(\'imagename\') imagename,
// @Res() res,
// ): Observable<Object> {
// return of(res.sendFile(join(process.cwd(), \'.assets/\' + imagename)));
// }
}
前端 html 代码。我正在获取所有信息,但不是图像,这里我提供src in img tag to display images
<div class=\"grid\" *ngFor=\"let result of results\">
<div class=\"blog-card spring-fever\" style=\"padding: 0.5rem; z-index: 100\">
<img
class=\"image\"
src=\"http://localhost:3000/{{ result.coverimage }}\"
alt=\"\"
height=\"400px\"
width=\"250px\"
style=\"border: 1px solid red\"
/>
<div class=\"title-content\">
<h3>
<a href=\"#\">{{ result?.name }}</a>
</h3>
<div class=\"intro\">
<h5>
<a>Author<b>:</b> {{ result?.author }}</a>
</h5>
<h5>
<a>Price<b>:</b> Rs{{ result?.price }}</a>
</h5>
<h5>
<a>Genre<b>:</b> {{ result?.genres_name }}</a>
</h5>
</div>
</div>
当我尝试这样src=\"{{result.coverimage}}\" 或[src]=\"result.coverimage\" 时,我得到错误localhost:4200/assets/imagename not found(404)。好吧,这很明显!因为没有这样的路径,所以 4200 是 Angular 的。但是我正在将图像上传到位于localhost:3000/assets/ 的后端资产文件夹中,我们总是将文件上传到后端以从数据库中获取动态方法