feat: show the blob list by game title and adapt with the UI

This commit is contained in:
lzh
2023-12-15 01:55:29 +08:00
parent cc16713972
commit bb4b64d073
5 changed files with 123 additions and 35 deletions
+3
View File
@@ -4,6 +4,8 @@ import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './pages/login/login.component';
import { PageNotFoundComponent } from './pages/pageNotFound.component';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';
const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: '/login' },
{
@@ -21,6 +23,7 @@ const routes: Routes = [
@NgModule({
imports: [RouterModule.forRoot(routes)],
providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }],
exports: [RouterModule],
})
export class AppRoutingModule {}
+5
View File
@@ -24,3 +24,8 @@ $baseColor: #d98410;
::ng-deep .ant-pagination-item:hover a {
color: $baseColor;
}
::ng-deep .image-card img {
max-width: 100%;
height: auto;
}
@@ -41,20 +41,38 @@
</div>
</div>
<!-- Drag and Drop Upload Section -->
<nz-upload
nzType="drag"
[nzMultiple]="true"
[nzBeforeUpload]="beforeUpload"
(nzChange)="handleChange($event)"
>
<p class="ant-upload-drag-icon">
<i nz-icon nzType="inbox"></i>
</p>
<p class="ant-upload-text">Click or drag file to this area to upload</p>
<p class="ant-upload-hint">
Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files
</p>
</nz-upload>
<button (click)="handleUpload()" [disabled]="uploading">Upload</button>
<div class="upload-section">
<nz-upload
nzType="drag"
[nzMultiple]="true"
[nzBeforeUpload]="beforeUpload"
(nzChange)="handleChange($event)"
class="upload-box"
>
<p class="ant-upload-drag-icon">
<i nz-icon nzType="inbox"></i>
</p>
<p class="ant-upload-text">Click or drag your videos or photos to this area to upload</p>
<p class="ant-upload-hint">
Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files
</p>
</nz-upload>
<button nz-button nzType="primary" (click)="handleUpload()" [disabled]="uploading">Upload</button>
<nz-spin [nzSpinning]="uploading"></nz-spin>
<ul>
<li *ngFor="let file of fileList">{{ file.name }}</li>
</ul>
</div>
<h3 style="margin-top: 20px;">Wonderful moments</h3>
<nz-row nzGutter="16">
<nz-col nzSpan="8" *ngFor="let item of images">
<nz-card [nzHoverable]="true">
<img *ngIf="item.type.startsWith('image')" [src]="item.url" alt="Uploaded Image" />
<video *ngIf="item.type.startsWith('video')" [src]="item.url" controls></video>
<nz-card-meta [nzTitle]="'Upload by ' + username"></nz-card-meta>
</nz-card>
</nz-col>
</nz-row>
@@ -6,9 +6,10 @@ import { NavigateService } from 'src/app/services/navigate.service';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
// 引入Azure存储相关的库
import { BlobServiceClient, ContainerClient }from '@azure/storage-blob';
import { BlobServiceClient, ContainerClient } from '@azure/storage-blob';
import { NzUploadChangeParam, NzUploadFile } from 'ng-zorro-antd/upload';
import { HttpClient } from '@angular/common/http';
import { lastValueFrom } from 'rxjs';
@Component({
selector: 'app-game-details',
templateUrl: './game-details.component.html',
@@ -21,22 +22,31 @@ export class GameDetailsComponent implements OnInit {
isAdmin: boolean = false;
uploading = false;
fileList: NzUploadFile[] = [];
username: any;
images: { url: any, type: any }[] = [];
// Azure Storage SAS URL
sasUrl = 'https://medias.blob.core.windows.net/assets?si=asset&sv=2022-11-02&sr=c&sig=OA8DpIpkl1ak4ZG%2BA7BzMtIRbI6carOTxLtzAcHa9pg%3D';
sasToken = 'si=asset&sv=2022-11-02&sr=c&sig=OA8DpIpkl1ak4ZG%2BA7BzMtIRbI6carOTxLtzAcHa9pg%3D'
containerName = 'assets'; // Container name
blobServiceClient: BlobServiceClient;
containerClient: ContainerClient;
constructor(
private route: ActivatedRoute,
private apiService: ApiService,
private $message: NzMessageService,
private navigateService: NavigateService,
public router: Router,
private fb: FormBuilder
) {}
private fb: FormBuilder,
private http: HttpClient
) {
this.blobServiceClient = new BlobServiceClient(this.sasUrl);
this.containerClient = this.blobServiceClient.getContainerClient(this.containerName);
}
ngOnInit(): void {
this.isAdmin = localStorage.getItem('username') === 'admin';
this.gameInfo = JSON.parse(localStorage.getItem('gameInfo') as any);
this.username = localStorage.getItem('username') as any;
this.editForm = this.fb.group({
Title: [null, [Validators.required]],
'Original Price': [null, [Validators.required]],
@@ -46,6 +56,7 @@ export class GameDetailsComponent implements OnInit {
'Release Date': [null, [Validators.required]],
'Game Description': [null, [Validators.required]],
});
this.loadImagesFromAzure();
}
// Handle the file before uploading
@@ -56,11 +67,19 @@ export class GameDetailsComponent implements OnInit {
// Perform the upload
handleUpload(): void {
this.uploadFilesToAzure(this.fileList);
this.uploading = true;
this.fileList.forEach(file => {
const reader = new FileReader();
reader.onload = (e: any) => {
const blob = new Blob([e.target.result], { type: file.type });
this.uploadFileToAzure(file.name, blob);
};
reader.readAsArrayBuffer(file as any);
});
}
// Handle file change event for drag-and-drop
handleChange({ file, fileList }: NzUploadChangeParam): void {
// Handle file change event for drag-and-drop
handleChange({ file, fileList }: NzUploadChangeParam): void {
const status = file.status;
if (status !== 'uploading') {
console.log(file, fileList);
@@ -73,19 +92,61 @@ export class GameDetailsComponent implements OnInit {
}
// Upload files to Azure Blob Storage
async uploadFilesToAzure(files: NzUploadFile[]) {
const blobServiceClient = new BlobServiceClient(this.sasUrl);
const containerName = 'assets'; // Container name
const containerClient = blobServiceClient.getContainerClient(containerName);
async uploadFileToAzure(fileName: string, blob: Blob) {
try {
for (const file of files) {
const blockBlobClient = containerClient.getBlockBlobClient(file.name!);
await blockBlobClient.uploadData(file.originFileObj as Blob);
this.$message.success(`${file.name} uploaded successfully.`);
}
// Get username and title
const username = localStorage.getItem('username');
const title = JSON.parse(localStorage.getItem('gameInfo') as any).Title;
// Add username and title to the file name
const newFileName = `${title}_${username}_${fileName}`;
// Create a new FileReader object
const blockBlobClient = this.containerClient.getBlockBlobClient(newFileName);
// Upload the ArrayBuffer to Azure Blob Storage
await blockBlobClient.uploadData(blob);
//await blockBlobClient.uploadData(file.originFileObj as Blob);
this.$message.success(`${fileName} uploaded successfully.`);
} catch (error) {
this.$message.error(`Upload failed: ${error}`);
}
this.fileList = [];
this.uploading = false;
}
async loadImagesFromAzure() {
const containerUrl = 'https://medias.blob.core.windows.net/assets';
const query = '?restype=container&comp=list'; // SAS token
const fullUrl = `${containerUrl}${query}`;
try {
const response = await lastValueFrom(this.http.get(fullUrl, { responseType: 'text' }));
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(response, 'text/xml');
const blobs = xmlDoc.getElementsByTagName('Blob');
this.images = [];
for (let i = 0; i < blobs.length; i++) {
const blob = blobs[i];
console.log("###########")
const name = blob.getElementsByTagName('Name')[0].textContent || '';
const title = JSON.parse(localStorage.getItem('gameInfo') as any).Title;
console.log(name);
console.log(title);
if (!name || name.includes(title)) {
const blobUrl = `${containerUrl}/${name}${this.extractSasToken()}`;
// Assuming you want to display images
this.images.push({ url: blobUrl, type: 'image/jpeg' }); // Modify 'type' as needed
}
}
} catch (error) {
console.error('Error fetching blobs:', error);
}
}
private extractSasToken(): string {
// Extract the SAS token from your sasUrl
const sasToken = this.sasUrl.split('?')[1];
return sasToken ? `?${sasToken}` : '';
}
}
@@ -4,12 +4,13 @@ import { RouterModule } from '@angular/router';
import { SharedModule } from '../../../shared/shared.module';
import { GameDetailsComponent } from './game-details.component';
import { NzUploadModule } from 'ng-zorro-antd/upload';
import { NzCardModule } from 'ng-zorro-antd/card';
@NgModule({
imports: [
CommonModule,
SharedModule,
NzUploadModule,
NzCardModule,
RouterModule.forChild([
{
path: '',