Never stop learning, approaching the AI
  • 😄About
  • 🅰️AI-Candy on YouTube
    • 🎬YouTube 视频列表
    • 💠AI项目本地部署
      • 1️⃣安装 Pytorch 运行环境
      • 2️⃣在Python虚拟环境下使用 VS Code or PyCharm
        • VS Code Python format
      • 3️⃣Create python virtual environment in Linux
    • 👽AI 入门系列课程
      • 0️向量及向量运算
        • Reshape array code
      • 1️人工智能,机器学习,深度学习 和神经网络的区别
      • 2️卷积神经网络(CNN)
        • 3D CNN sample code
      • 3️Transformer 原理
      • 4️前馈神经网络 (FNN)
  • 🎭Artificial intelligence
    • 1️⃣Deep learning / machine learning
      • 👉Deep Learning Resources
      • 👉Deep learning notes
    • 2️⃣Python
      • Youtube音乐下载
      • Pytorch 安装环境配置 (old)
        • TorchEEG
      • Anaconda3 Python path
      • Data
      • IEEE-754 Floating Point Converter
        • ieee 754 conversion function
      • 文件读写
      • 文本清理
      • Python 下载在线视频
      • 修改Jupyter Notebook 默认工作目录
    • 3️⃣AI Websites
  • 🪤Programming
    • SQL
      • Delete data and reset auto-increment ID
    • Angular
      • Angular-datatables, dd/MM/yyyy, sorting (no paged list)
      • Datatables save state using localStorage
      • Variable storage method
      • Colour picker
      • Error fix for click columns on Datatable
      • Auto address use Google place
      • Auto address use Azure Maps
      • Upload file to Server
      • Validators.required OnChange input
      • Date, Time field
      • VS Code: Auto add missing imports when save
      • Datatable setting
      • Date time format
      • sticky <th> and <td> content
      • Filter booked time
      • Dropdown time selection with interval
      • Angular date online test
      • Updating data without refreshing the page
      • Object array sort and sum
      • Multi-type of columns use in one column
      • Select button for datatables
      • Switch button and event
      • Delete column from Array
      • Three-layer structure
      • Remove shadow when print mat-dialog content
      • JSON Parse && Object Array
      • Detect unused import in Typescript
      • Change location using radio button
      • display multi line message in the Toastr
      • Custom LOCALE_ID
      • Batch add data from csv to API server
        • Angular read csv and upload to Server
      • USB Port reader Web solution
      • Debug Angular app using JavaScript Debugger in VS Code
      • Skills
        • FormData & FormGroup to JSON
        • Dropdown list (customer)
        • Get current datetime
        • Get first day of year, month, and date
        • Call a function in a forEach loop
        • disable and readonly
        • Form element value
        • HTML input type
        • Input pattern (validation)
      • Display pipe (UI format)
        • Input upper case and button checked
        • Icons (Bootstrap and CoreUI)
        • Page Refresh
        • Selection list (two ways)
        • onChange Selection event
        • Random Password and Toggle
        • Password match
        • Select checkbox disable
      • Print and save to PDF
      • Import JS into Angular
      • LocalStorage
      • Angular DataTable
        • Data sort
        • A sample usage
        • Angular DataTable server side big data query
      • Change chart.js chart type
      • Angular UI - .NET API - .NET Auth
      • Angular - .NET API
      • *ngIf else && change to @if
      • Angular add reCAPTCHA v3 (Google)
      • Angular update
        • Update from v13 to v15
        • Update from v15 to v18
      • Angular application version central
      • Face detection
        • Face-api.js
      • Angular, Node version compatibility matrix
      • Clear cache
      • Angular oauth2 OIDC
      • Angular add header
    • .NET Skills
      • Add ID manually
      • Auto Mapping
        • Ignore Nesting
        • Startup setting
        • Datetime processing in AutoMapping
        • AutoMapper example
      • Validation filter
      • BaseController
      • Group by many
      • Database first, scaffold to class
      • Log setting and exception handler
      • Update appsetting.json value
      • Azure service bus message (queue)
      • Read appsetting.json value
      • Auth get user info by email
      • Azure Time zone
      • .NET API Add Service
      • Object comparison
      • Coravel Schedule
        • Read appsettings.json
      • .Net Core RDLC Report, Coravel and Email
      • Check Network and SQL server connections.
      • Datatime custom format
      • Many to Many EF
        • Many to Many CheckBox
      • PDFpig: Send Email with PDF attachment
      • .NET Core Middleware order
      • .NET API add Worker Service
      • .NET Router
      • Partial columns update
      • Add and Delete
      • 图片自适应宽度
      • ASP.NET Identity
      • Upload file to Azure
        • Upload file to Blob
      • Developer Guide
      • Code first one-many
      • ASP.NET MVC 5 Custom Error Page
      • VS can't debug
      • 通过邮编查 NSW COVID-19 感染人数
      • Jquery File Upload
      • Jquery Datepicker
      • ajax delete file from server
      • Autofac in MVC
      • Autofac in .NET Core
      • .NET Core
      • HTTP Return code
      • IdentityServer4
    • Power BI
      • Add parameter to PowerBI report
      • Convert UTC to Local time
      • Python in PowerBI
        • IEEE-754 conversion
      • PowerBI embed app - Server
      • PowerBI embed app - Client
        • Setting on portal
    • Azure service
      • Key Vault
      • Service bus - queue
      • Power Automate
      • Kusto Query Language
      • Azure Data Explorer
      • Reserved keyword on Azure Error
      • SQL Azure time convert
    • Azure blob
      • Azure blob setting
      • Display image from Blob
      • Upload image to Blob through .NET API
    • Html Bootstrap Icon, colour, size
      • Html spacing
      • Html text alignment
    • Video stream - JsMpeg
      • SSL - generate key
      • Client (SSL)
      • Websocket-Server (SSL)
      • Play RTSP video stream
    • ⏰Time Zone
      • datetime-local set date range
      • 🕐Get data by local time (UI, API)
      • 🕑Add offset hours for local UI and report
      • 🕒UTC time and Datetime convert
      • 🕓Angular - Timezone selection
      • 🕔Angular - Convert UTC to local time
      • 🕕C# Time Zone
  • >>>>>>>>>>>>>>>>>>>>>>>>>>>>
  • 🪜Apps and Skills
    • 1️Windows system app skills
      • Brother HL-2130 打印机 Toner 报警
      • VS Code 快捷键
      • Check SHA256 on windows
      • blob 视频下载
      • Photoshop 制作证件照片
      • 获取 Windows Key
      • 10进制36进制互转
      • Error when publish to Azure
      • Disable windows automatic update
      • Outlook setup for Yahoo Email
      • IIS setting
      • Windows 8/10, IIS Service
      • 安装程序出错 2052,2053 报警
      • 6 Yao Chinese UI
    • 2️Linux command
    • 3️Git command
    • 4️Bitbucket
    • 5️Gitbook Skills
    • 6️GitHub Desktop
    • 7️⃣EndNote
      • EndNote V21
      • Endnote使用技巧
      • 批量删除/修改Endnote 中 notes 栏内容
  • Android mobile connect PC
  • 💎USEFUL LINKS
    • 1️Coding websites
      • Website links
    • 2️Windows 平台工具,网站
    • 3️PotPlayer 设置
  • >>>>>>>>>>>>>>>>>>>>>>>>>>>>
  • 🚩Research >>EEG
    • 1️EEG基本知识的理论介绍
      • EEG 简介
      • EEG 的节律信号
      • EEG电极帽
      • EEG 伪迹
      • ERP 介绍
      • ERP 成分
      • EEG 数据分析软件
    • 2️LSL 应用
    • 3️EEG公开数据集汇总整理
    • 4️REDCap
      • Migration (Export & Import)
    • 5️⃣ScaneR
  • ☕Buy me a coffee
Powered by GitBook
On this page

Was this helpful?

  1. Programming
  2. .NET Skills
  3. Upload file to Azure

Upload file to Blob


"ConnectionStrings": {
    "AzureBlobConnectionString": "DefaultEndpointsProtocol=https;AccountName=mooreroad;AccountKey=I4ap+8CbAEsNb3ozn2xK87vsisJVK7RvXTLgq0xRSJywc8ov6tggOFp5TamPTTuuRDaP4pgnRiMj+AStdmuy7g==;EndpointSuffix=core.windows.net"
  },
  
  "BlobConfiguration": {
    "BlobContainerName": "document-location",
    "BlobUrl": "https://mooreroad.blob.core.windows.net/"
    //"BlobContainerSystemSetting": "systemsetting-web",
  },
  • Microsoft Azure>Storage accounts (Create account, then Create Container that select Blob)

  • "AzureBlobConnectionString": name ->Security + networking ->Access keys->key1 -》Connection string

  • "BlobContainerName": name ->Data storage->Containers->container name

  • "BlobUrl": container name-> Settings->Properties

// Repository

 public class BlobRepository : IBlobRepository
 {
     private readonly BlobServiceClient _blobServiceClient;
     private readonly IAppSettingService _appSettingService;
     private readonly List<string> ImageExtensions = new List<string> { "JPG", "JPEG", "PNG" };
     private readonly string blockSectionName = "BlobConfiguration";

     public BlobRepository(BlobServiceClient blobServiceClient, IAppSettingService appSettingService)
     {
         _blobServiceClient = blobServiceClient;
         _appSettingService = appSettingService;
     }

     public async void DeleteBlob(string url, string blobContainerKey)
     {
         BlobContainerClient client = getBlobContainerClient(blobContainerKey);
         var fileName = new Uri(url).Segments.LastOrDefault();
         var blobClient = client.GetBlobClient(fileName);
         await blobClient.DeleteIfExistsAsync();
     }

     public string GetBlobURL(string blobContainerKey)
     {
         string blobContainerValue = _appSettingService.GetAppSettingChildrenValueBySectionKey(blockSectionName, blobContainerKey);
         string url = _appSettingService.GetAppSettingChildrenValueBySectionKey(blockSectionName, "BlobUrl");
         return url + '/' + blobContainerValue + "/";
     }

     public string GetLocalBlobURL(string blobContainerKey)
     {
         string blobContainerValue = _appSettingService.GetAppSettingChildrenValueBySectionKey(blockSectionName, blobContainerKey);
         string url = _appSettingService.GetAppSettingChildrenValueBySectionKey(blockSectionName, "BlobUrl");
         return url + blobContainerValue + "/";
     }

     public async Task<BlobObject> GetBlobFile(string url, string blobContainerKey)
     {
         BlobContainerClient client = getBlobContainerClient(blobContainerKey);
         var fileName = new Uri(url).Segments.LastOrDefault();

         try
         {
             var blobClient = client.GetBlobClient(fileName);
             if (await blobClient.ExistsAsync())
             {
                 BlobDownloadResult content = await blobClient.DownloadContentAsync();
                 var downloadedData = content.Content.ToStream();
                 string fileExtensionName = Path.GetExtension(fileName.ToUpperInvariant()).Replace(".", "");

                 if (ImageExtensions.Contains(fileExtensionName))
                 {
                     var extension = Path.GetExtension(fileName);
                     return new BlobObject { Content = downloadedData, ContentType = "image/" + extension.Remove(0, 1) };
                 }
                 else
                 {
                     return new BlobObject { Content = downloadedData, ContentType = content.Details.ContentType };
                 }
             }
             else
             {
                 return null;
             }
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
             return null;
         }
     }

     public async Task<List<string>> ListBlobs(string blobContainerKey)
     {
         BlobContainerClient client = getBlobContainerClient(blobContainerKey);
         List<string> list = new List<string>();

         await foreach (var blobItem in client.GetBlobsAsync())
         {
             list.Add(blobItem.Name);
         }

         return list;
     }

     public async Task<string> UploadBlobFile(string filePath, string fileName, string blobContainerKey)
     {
         BlobContainerClient client = getBlobContainerClient(blobContainerKey);
         var blobClient = client.GetBlobClient(fileName);
         var status = await blobClient.UploadAsync(filePath);
         Console.WriteLine(status);

         return blobClient.Uri.AbsoluteUri;
     }


     public async Task<string> UploadFileStreamToBlob(string fileName, IFormFile file, string blobContainerKey)
     {
         var containerClient = getBlobContainerClient(blobContainerKey);
         var blobClient = containerClient.GetBlobClient(fileName);

         using (var stream = file.OpenReadStream())
         {
             // upload file stream to blob
             var status = await blobClient.UploadAsync(stream, overwrite: true);
             Console.WriteLine(status);
             if (status.GetRawResponse().Status == 201)
             {
                 return blobClient.Uri.AbsoluteUri;
             }
         }

         return null;
     }


     public async Task<string> UploadBase64ImageToBlob(string base64Image, string blobContainerKey)
     {

         // Generate a unique file name
         string guIdString = Guid.NewGuid().ToString();
         string fileSuffix = base64Image.Substring(base64Image.IndexOf("/") + 1, base64Image.IndexOf(";base64") - base64Image.IndexOf("/") - 1);

         if (ImageExtensions.Contains(fileSuffix.ToUpper()))
         {
             string imageFileName = guIdString + '.' + fileSuffix;

             var result = await UploadBlobImage(imageFileName, base64Image, blobContainerKey);
             if (result != null)
             {
                 /*
                   var returnData = new { link = result };
                   string jsonData = JsonConvert.SerializeObject(returnData);
                   string url = JObject.Parse(jsonData)["link"].ToString();
                 */
                 return imageFileName;
             }
         }

         return null;
     }

     public async Task<string> UploadBlobImage(string fileName, string image, string blobContainerKey)
     {
         BlobContainerClient client = getBlobContainerClient(blobContainerKey);

         var encodedImage = image.Split(',')[1];
         var decodedImage = Convert.FromBase64String(encodedImage);

         var blobClient = client.GetBlobClient(fileName);

         using (var fileStream = new MemoryStream(decodedImage))
         {
             // upload image stream to blob
             var status = await blobClient.UploadAsync(fileStream, true);
             Console.WriteLine(status);
             if (status.GetRawResponse().Status == 201)
             {
                 return blobClient.Uri.AbsoluteUri;
             }
         }

         return null;
     }


     private BlobContainerClient getBlobContainerClient(string blobContainerKey)
     {
         string blobContainerValue = _appSettingService.GetAppSettingChildrenValueBySectionKey(blockSectionName, blobContainerKey);
         BlobContainerClient client = _blobServiceClient.GetBlobContainerClient(blobContainerValue);

         return client;
     }
 }

// Controller

  [ApiController]
  [Authorize]
  public class BlobStorageController : BaseController<BlobStorageController>
  {
      private readonly IBlobRepository _blobRepository;

      public BlobStorageController(IBlobRepository blobRepository)
      {
          _blobRepository = blobRepository;
      }

      [HttpGet("api/blob/image/{fileName}/{blobContainerKey}")]
      public async Task<IActionResult> GetBlobFile(string fileName, string blobContainerKey)
      {
          string url = _blobRepository.GetBlobURL(blobContainerKey);
          BlobObject result = await _blobRepository.GetBlobFile(url + fileName, blobContainerKey);
          if (result != null)
          {
              var fileStreamResult = File(result.Content, result.ContentType);
              return fileStreamResult;
          }

          return BadRequest();
      }

      [HttpPost]
      [Route("api/blob/upload/file")]
      public async Task<IActionResult> UploadBlobFile(BlobFileModel model)
      {
          if (model.File == null || model.File.Length == 0)
          {
              return BadRequest("No file uploaded.");
          }

          var result = await _blobRepository.UploadFileStreamToBlob(model.FileName, model.File, model.BlobContainerKey);
          if (result != null)
          {
              var returnData = new { link = result };
              string jsonData = JsonConvert.SerializeObject(returnData);
              return Ok(jsonData);
          }

          return StatusCode(500, "Failed to upload file.");
      }

      [HttpPost]
      [Route("api/blob/upload/image")]
      public async Task<IActionResult> UploadBlobImage(BlobImageModel model)
      {
          var result = await _blobRepository.UploadBlobImage(model.FileName, model.Image, model.BlobContainerKey);

          if (result != null)
          {
              var returnData = new { link = result };
              string jsonData = JsonConvert.SerializeObject(returnData);
              return Ok(jsonData);
          }

          return BadRequest();
      }

      [HttpPost]
      [Route("api/blob/upload/64image")]
      public async Task<IActionResult> UploadBlob64Image(BlobImageModel model)
      {
          var result = await _blobRepository.UploadBase64ImageToBlob(model.Image, model.BlobContainerKey);

          if (result != null)
          {
              var returnData = new { link = result };
              string jsonData = JsonConvert.SerializeObject(returnData);
              return Ok(jsonData);
          }

          return BadRequest();
      }


      [HttpDelete("api/blob/delete/{blobContainerKey}")]
      public IActionResult DeleteBlob(string url, string blobContainerKey)
      {
          _blobRepository.DeleteBlob(url, blobContainerKey);
          return Ok();
      }

      [HttpGet("api/blob/list/{blobContainerKey}")]
      public async Task<IActionResult> ListBlobs(string blobContainerKey)
      {
          var result = await _blobRepository.ListBlobs(blobContainerKey);
          return Ok(result);
      }
  }

```html
<h2 mat-dialog-title align="center" class="text-success pb-0 ">Upload file </h2>
<h5 align="center">(PDF or MS Word document only)</h5>
<div><b class="ps-4 mb-2"> Location: </b> <span class="text-info"> {{data.name}}</span></div>
<hr>

<div class="controls">
  @if(isLoading){
  <mat-progress-bar mode="indeterminate" color="primary" aria-label="Loading content"> </mat-progress-bar>
  }
</div>

<form [formGroup]="frm" (ngSubmit)="onSubmit(frm)">
  <mat-dialog-content>
    <div class="form-group mb-3">
      <input type="file" class="file-input" name="input" id="txtFileUpload" (change)="uploadListener($event)"
        accept=".doc, .pdf, .docx" />
    </div>

    <div class="form-group" hidden>
      <label>BlobContainerKey</label>
      <input class="form-control" [attr.disabled]="true" formControlName="blobContainerKey">
    </div>
    <div class="form-group mb-2">
      <label>Name</label> <span style="color: red;"> *</span>
      <input class="form-control" formControlName="name">
    </div>
    <div class="form-group mb-3">
      <label>Description</label>
      <textarea rows="2" class="form-control" formControlName="description"></textarea>
      </div>
     <hr>
    <div><span style="color: red;">*</span> is required</div>
  </mat-dialog-content>
  <div mat-dialog-actions align="center">
    <button class="btn btn-block btn-outline-secondary btn-sm" mat-button mat-dialog-close>Cancel</button>
    <span>&nbsp; &nbsp; </span> <span>&nbsp; &nbsp; </span>
    <button type="submit" [disabled]="!frm.valid || submitClicked" class="btn btn-outline-warning btn-sm"
      mat-button>Upload</button>
  </div>
</form>

```

```typescript
import { Component, Inject, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { Subject } from 'rxjs';
import { BlobService } from 'src/app/services/blob.service';
import { LocationService } from 'src/app/services/location.service';
import { constants } from '../../../constants';

@Component({
  selector: 'app-location-document-add',
  templateUrl: './location-document-add.component.html',
  styleUrl: './location-document-add.component.scss'
})
export class LocationDocumentAddComponent {
  @ViewChild('csvReader') csvReader: any;
  public records: any[] = [];
  dtOptions: any = {};
  dtTrigger: Subject<any> = new Subject<any>();
  isLoading = false;
  submitClicked = false;
  headerTitle: any = [];
  frm!: FormGroup;
  csvRecordsArray: any;
  failedArray: any = [];
  successedCount = 0;
  Locations: any;
  selectedTenant: any;
  canImport = true;
  selectedFileName = '';
  is_edit: boolean = true;
  maxColumn = 4;   ///<<<<

  constructor(
    @Inject(MAT_DIALOG_DATA) public data: any,
    private locationService: LocationService,
    private blobService: BlobService,
    private toastr: ToastrService,
    public router: Router,
    public fb: FormBuilder,
    private dialog: MatDialog,
    private dialogRef: MatDialogRef<LocationDocumentAddComponent>
  ) { }

  ngOnInit(): void {
    this.frm = this.fb.group({
      name: ['', Validators.required],
      file: [],
      description: [],
      blobContainerKey: [{ value: constants.blobContainerKey, disabled: !this.is_edit }],
    });
  }

  uploadListener($event: any): void {
    let files = $event.srcElement.files;
    this.canImport = true;
    if (this.isValidFile(files[0])) {
      this.isLoading = true;
      this.selectedFileName = files[0].name;
      //  let input = $event.target;
      let reader = new FileReader();
      reader.readAsArrayBuffer(files[0])
      reader.onload = () => {
        this.frm.controls['name'].setValue(this.selectedFileName);
        this.frm.controls['file'].setValue(files[0]);
        this.isLoading = false;
      };

      reader.onerror = function () {
        console.log('error is occured while reading file!');
      };

    } else {
      this.selectedFileName = 'No file selected';
      alert("Please import valid .csv file.");
      this.fileReset();
    }
  }


  isValidFile(file: any) {
    if (file.name.endsWith(".pdf") || file.name.endsWith(".doc") || file.name.endsWith(".docx"))
      return true;
    else
      return false;
  }


  fileReset() {
    this.csvReader.nativeElement.value = "";
    this.records = [];
  }

  async onSubmit(frm: FormGroup) {
    this.submitClicked = true;
    this.isLoading = true;
    this.blobService.uploadFileToBlob(frm.value)
      .subscribe({
        next: data => {
          if (data.status == 200) {
            this.delayReLoad(this.router.url, 2000);  // 400 ms
          }
        },
        error: error => {
          console.error('Error uploading file', error);
          this.toastr.error('Error uploading file', 'Error')
          this.isLoading = false;
        }
      });
  }

  async reload(url: string): Promise<boolean> {
    await this.router.navigateByUrl('weighing', { skipLocationChange: true });
    return this.router.navigateByUrl(url);
  }

  // delay ms
  async delayReLoad(url: string, ms: any) {
    setTimeout(() => {
      this.isLoading = false;
      this.dialogRef.close();
      this.toastr.success('File uploaded successfully !', 'Success', { timeOut: 2000 });
      this.reload(url);
    }, ms);
  }


}

```
PreviousUpload file to AzureNextDeveloper Guide

Last updated 3 months ago

Was this helpful?

🪤