我的旅行表串列顯示了除影像 Cover之外的所有必需資訊。我無法弄清楚為什么影像路徑被破壞了。我懷疑我的后端代碼為我的靜態檔案提供服務,但據我所知,一切似乎都很好。
在后端代碼中,我有以下代碼行用于在我的 app.js 檔案中提供靜態檔案。
app.use(
'/public/img/countries',
express.static(`${__dirname}/public/img/countries`)
);
app.use('/public/img/tours', express.static(`${__dirname}/public/img/tours`));
app.use('/public/img/users', express.static(`${__dirname}/public/img/users`));
在我的游覽處理程式函式 tourController.js 后端代碼中,我有以下代碼,因為它專門與影像有關。
const multerStorage = multer.memoryStorage();
const multerFilter = (req, file, cb) => {
if (file.mimetype.startsWith('image')) {
cb(null, true);
} else {
cb(new AppError('Not an image! Please upload only images.', 400), false);
}
};
const upload = multer({
storage: multerStorage,
fileFilter: multerFilter
// limits: { fileSize: maxSize }
});
exports.uploadTourImages = upload.fields([
//req.files for fields
{ name: 'imageCover', maxCount: 1 },
{ name: 'images', maxCount: 3 }
]);
exports.resizeTourImages = catchAsync(async (req, res, next) => {
if (!req.files.imageCover || !req.files.images) return next();
// 1) Cover image
req.body.imageCover = `tour-${req.params.id}-${Date.now()}-cover.jpeg`;
await sharp(req.files.imageCover[0].buffer)
.rotate()
.resize(1903, 1268)
.toFormat('jpeg')
.jpeg({ quality: 90 })
.toFile(`public/img/tours/${req.body.imageCover}`);
req.body.images = [];
await Promise.all(
req.files.images.map(async (file, i) => {
const filename = `tour-${req.params.id}-${Date.now()}-${i 1}.jpeg`;
await sharp(file.buffer)
.rotate()
.resize(1903, 1268)
.toFormat('jpeg')
.jpeg({ quality: 90 })
.toFile(`public/img/tours/${filename}`);
req.body.images.push(filename);
})
);
next();
});
在我的后端模型上的工廠功能上
exports.getAll = Model =>
catchAsync(async (req, res, next) => {
let filter = {};
if (req.params.tourId) filter = { tour: req.params.tourId };
//EXECUTE QUERY
const features = new APIFeatures(Model.find(filter), req.query)
.filter()
.sort()
.limitFields()
.paginate();
const doc = await features.query;
//SEND REPONSE
res.status(200).json({
status: 'success',
results: doc.length,
data: {
data: doc
}
});
next();
});
在我的前端,我的 tour-list.component.html 上有我的表的以下代碼
<p-table [value]="tours" styleClass="p-datatable-gridlines" responsiveLayout="scroll">
<ng-template pTemplate="header">
<tr>
<th pSortableColumn="name">Name<p-sortIcon field="name"></p-sortIcon></th>
<th>Image Cover</th>
<th pSortableColumn="price">Price<p-sortIcon field="price"></p-sortIcon></th>
<th pSortableColumn="ratingsAverage">
Ratings Average <p-sortIcon field="ratingsAverage"></p-sortIcon>
</th>
<th pSortableColumn="country">Country<p-sortIcon field="country"></p-sortIcon></th>
<th pSortableColumn="difficulty">
Difficulty<p-sortIcon field="difficulty"></p-sortIcon>
</th>
<th pSortableColumn="availabilityDates">
Availability Dates<p-sortIcon field="availabilityDates"></p-sortIcon>
</th>
<th pSortableColumn="maxGroupPair">
Maximum Group Pairs<p-sortIcon field="maxGroupPair"></p-sortIcon>
</th>
<th pSortableColumn="minimumAge">
Minimum Age<p-sortIcon field="minimumAge"></p-sortIcon>
</th>
<th pSortableColumn="dateCreated">
Date Created<p-sortIcon field="dateCreated"></p-sortIcon>
</th>
<th></th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-tour>
<tr>
<td>{{ tour.name }}</td>
<td><img [src]="tour.imageCover" width="100px" height="67px" alt="" /></td>
<td>{{ tour.price }}</td>
<td>{{ tour.ratingsAverage }}</td>
<td>{{ tour.country.name }}</td>
<td>{{ tour.difficulty }}</td>
<td>{{ tour.availabilityDates }}</td>
<td>{{ tour.maxGroupPair }}</td>
<td>{{ tour.minimumAge }}</td>
<td>{{ tour.dateCreated | date: 'longDate' }}</td>
</tr>
</ng-template>
</p-table>
我的 tours-list.component.ts 檔案有以下代碼
import { Component, OnInit } from '@angular/core';
import { ToursService } from '@tourafrika/tours';
@Component({
selector: 'admin-tours-list',
templateUrl: './tours-list.component.html',
styles: []
})
export class ToursListComponent implements OnInit {
tours = [];
constructor(private tourService: ToursService) {}
ngOnInit(): void {
this._getTours();
}
private _getTours() {
this.tourService.getTours().subscribe((tours) => {
this.tours = tours;
});
}
}
我前端的庫模型代碼具有以下代碼。
import { Country } from './country';
import { User } from './user';
export class Tour {
id?: string;
name?: string;
slug?: string;
country?: Country;
duration?: number;
maxGroupPair?: number;
singleSupplement?: number;
difficulty?: string;
ratingsAverage?: number;
ratingsQuantity?: number;
price?: number;
priceDiscount?: number;
overview?: string;
imageCover?: string;
images?: string[];
dateCreated?: string;
availabilityDates?: string[];
isFeatured?: boolean;
secretTour?: string;
minimumAge?: string;
departureLocation?: string;
locations?: string;
guides?: [User];
}
export interface ITourListResponse {
status: string;
results: number;
data: { data: Tour[] };
}
My services file of tours.service.ts has the below code.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Tour, ITourListResponse } from '../models/tour';
import { map } from 'rxjs/operators';
import { environment } from '@env/environment';
@Injectable({
providedIn: 'root'
})
export class ToursService {
apiURLTours = environment.apiUrl 'tours';
constructor(private http: HttpClient) {}
getTours(): Observable<Tour[]> {
return this.http
.get<ITourListResponse>(this.apiURLTours)
.pipe(map((response: ITourListResponse) => response.data.data));
}
Thanks!
uj5u.com熱心網友回復:
通過運行以下代碼重新定義我的 imageCover 路徑,我已經通過在后端的 toursController.ts 檔案中完全重構我的代碼來解決這個問題。現在一切都好!
const { file } = req;
let imagepath;
if (file) {
const fileName = req.file.filename;
const basePath = `${req.protocol}://${req.get('host')}/public/img/tours/`;
imagepath = `${basePath}${fileName}`;
} else {
imagepath = tour.imageCover;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/422740.html
標籤:
