Skip to content

Instantly share code, notes, and snippets.

@Byte-Forge-AI
Last active February 27, 2024 13:34
Show Gist options
  • Select an option

  • Save Byte-Forge-AI/206066f4701dc6f661efc0abc12b9798 to your computer and use it in GitHub Desktop.

Select an option

Save Byte-Forge-AI/206066f4701dc6f661efc0abc12b9798 to your computer and use it in GitHub Desktop.
Angular 11 and above, Azure Blob-Storage-CRUD operations

Angular 11 and Above Azure Blob-Storage CRUD Operations

features list

  • listing containers
  • creating containers
  • uploading files
  • listing files
  • deleting files

How to add to existing app

<h1>
List Containers
</h1>
<button (click)="getContainers()">List Container</button>
<input type="text" name="containername" id="contname" #contname>
<button (click)="create(contname.value)">Add Container</button>
<ul>
<li *ngFor="let container of containers" (click)="listFiles(container)">{{container}}<button (click)="deleteContainer(container)">delete</button></li>
</ul>
<h1>List Files</h1>
<ul>
<li *ngFor="let item of listItems">{{item.name}} <button (click)="delete(item.name)">delete</button></li>
</ul>
<input type="file" name="upload" multiple id="uploadID" #file />
<button (click)="upload(file)" >upload</button>
import { OnInit } from '@angular/core';
import { Component } from '@angular/core';
import { getContainers, createContainer, listBlob, BLOBItem, CONTENT, uploadFile, deleteBlob } from './azure.storage';
@Component({
selector: 'app-root',
templateUrl: './azure.component.html'
})
export class AzureComponent implements OnInit {
title = 'azure demo-ng';
containers: any = [];
selectedContainer: string = '';
listItems: any = [];
constructor() {
}
ngOnInit(): void {
//Called after the constructor, initializing input properties, and the first call to ngOnChanges.
//Add 'implements OnInit' to the class.
}
async getContainers() {
getContainers().then((res: Array<string>) => {
this.containers = res;
})
}
upload(file: any) {
console.log(file.files.length);
if (file.files.length > 0) {
[...file.files].forEach((file: any) => {
let content: CONTENT = {
containerName: this.selectedContainer,
file: file,
filename: `${this.selectedContainer}-${Date.now()}.${file.name.split('.')[1]}`
};
uploadFile(content).then((res: string) => {
console.log(res);
})
console.log(file);
})
}
}
create(value: string) {
createContainer(value).then((resp) => {
console.log(resp);
});
}
async listFiles(containerName: string) {
this.selectedContainer = containerName;
listBlob(containerName).then((res: Array<BLOBItem>) => {
this.listItems = res;
console.log(res);
})
}
delete(value: string) {
deleteBlob(this.selectedContainer, value).then((resp: string) => {
console.log(resp);
});
}
deleteContainer(value: string) {
deleteContainer(value).then((resp: string) => {
console.log(resp);
});
}
}
import {
BlobServiceClient,
} from "@azure/storage-blob";
import { BlobItem } from '@azure/storage-blob';
import { environment } from "src/environments/environment";
const account = environment.ACCOUNT_NAME;
const accountKey = environment.SAS;
// BlobClientServiceString
const blobServiceClient = new BlobServiceClient(`https://${account}.blob.core.windows.net${accountKey}`);
export interface BLOBItem extends BlobItem { };
export interface CONTENT {
containerName: string; // desired container name
file: any; // file to upload
filename: string; // filename as desired with path
}
export async function getContainers() {
let containers = [];
let iter = blobServiceClient.listContainers();
let containerItem = await iter.next();
while (!containerItem.done) {
containers.push(containerItem.value.name);
containerItem = await iter.next();
}
return containers;
}
export async function createContainer(containername:any) {
const containerName = containername || `${new Date().getTime()}`;
const containerClient = blobServiceClient.getContainerClient(containerName);
try {
const createContainerResponse = await containerClient.create();
return `Create container ${containerName} successfully ${createContainerResponse.requestId}`;
}
catch (err) {
return {requestId: err.details.requestId, statusCode: err.statusCode, errorCode:err.details.errorCode}
}
}
export async function listBlob(containerName: string) {
// BlobContainerClient
const containerClient = blobServiceClient.getContainerClient(containerName);
let ListBlobs = [];
let iter = containerClient.listBlobsFlat();
let blobItem = await iter.next();
while (!blobItem.done) {
ListBlobs.push(blobItem.value);
blobItem = await iter.next();
}
return ListBlobs;
}
export async function deleteBlob(containerName: string, filename:string){
const containerClient = blobServiceClient.getContainerClient(containerName);
const blockBlobClient = containerClient.getBlockBlobClient(filename);
const deleteBlob = await blockBlobClient.delete();
return `Deleted Blob ${filename} successfully ${deleteBlob.requestId}`;
}
export async function deleteContainer(containerName:string){
const containerClient = blobServiceClient.getContainerClient(containerName);
const deleteContainer = await containerClient.delete();
return `Deleted Blob ${containerName} successfully ${deleteContainer.requestId}`;
}
export async function uploadFile(content: CONTENT) {
const containerClient = blobServiceClient.getContainerClient(content.containerName);
const blockBlobClient = containerClient.getBlockBlobClient(content.filename);
const uploadBlobResponse = await blockBlobClient.uploadBrowserData(content.file, {
maxSingleShotSize: 4 * 1024 * 1024,
blobHTTPHeaders: { blobContentType: content.file.type } // set mimetype
});
return `Upload block blob ${content.filename} successfully ${uploadBlobResponse.requestId}`;
}
@AdiRevivo
Copy link

Uploading 694900.png…

@ParthMDave
Copy link

Can you please give me some idea about "src/environments/environment" file with some dummy data.
I am confuse of having value of account & accountKey value

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment