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. Azure blob

Upload image to Blob through .NET API

Angular+ngx-dropzone send base64 image string to .NET API, encode, send image to Blob, get Url

PreviousDisplay image from BlobNextHtml Bootstrap Icon, colour, size

Last updated 1 year ago

Was this helpful?

-- copy "Base64 Image source" to upload using API

// upload.module.ts

``` 
    NgxDropzoneModule,      ///  ngx-dropzone
    ReactiveFormsModule,
    MatProgressBarModule
```
// upload.ts
 
import { throwDialogContentAlreadyAttachedError } from '@angular/cdk/dialog';
import { Component, OnInit } from '@angular/core';
import { UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { UploadService } from 'src/app/services/upload.service';

@Component({
  selector: 'app-upload-to-blob',
  templateUrl: './upload-to-blob.component.html',
  styleUrls: ['./upload-to-blob.component.scss']
})
export class UploadToBlobComponent implements OnInit {
  shortLink: string = "";
  loading: boolean = false; // Flag variable
  file: any; // Variable to store file
  imageValid: boolean = false;
  files: File[] = [];
  base64Image: any;

  constructor(
    private fileUploadService: UploadService,
    private toastr: ToastrService,

  ) { }

  ngOnInit(): void {

  }

  onSubmit() {
    this.loading = !this.loading;
    var jsonData = {
      "FileName": this.files[0].name,
      "Image": this.base64Image
    }

    this.fileUploadService.uploadImageToBlob(jsonData)
      .subscribe({
        next: (data) => {
          if (data.status == 200) {
            this.toastr.success('Upload image complate', 'Success');
            this.shortLink = data.body.link;
            this.loading = false; // Flag variable
          }
        },
        error: (error) => {
          //  console.log(error);
          this.toastr.warning(error.status + ' - upload image Fail', 'Fail');
        },
      });

  }

  onSelect(event: any) {
    console.log(event);
    this.files.length = 0;
    this.files.push(...event.addedFiles);
    let arrayLength = this.files.length;
    // keep one file
    this.files.splice(1, arrayLength - 1);

    if (arrayLength === 1) {
      this.imageValid = true;
      this.readFile(this.files[0]).then(fileContents => {
        // Put this string in a request body to upload it to an API.
        //  console.log(fileContents);
        this.base64Image = fileContents;
      })

    }
  }

  onRemove(event: any) {
    console.log(event);
    this.files.splice(this.files.indexOf(event), 1);
    this.imageValid = false;
  }


  private async readFile(file: File): Promise<string | ArrayBuffer> {
    return new Promise<string | ArrayBuffer>((resolve, reject) => {
      const reader = new FileReader();

      reader.onload = (e) => {
        return resolve((e.target as FileReader).result || '');
      };

      reader.onerror = e => {
        console.error(`FileReader failed on file ${file.name}.`);
        return reject(null);
      };

      if (!file) {
        console.error('No file to read.');
        return reject(null);
      }

      reader.readAsDataURL(file);
    });
  }

}

 
// upload.html

<ng-container>
  <div class="card border-success">
    <div class="card-header">
      Feature: Upload file to the Azure blob storage
    </div>
    <div class="card-body text-success">
      <div class="py-5 shadow">

        <div class="row justify-content-center">
          <div class="col-sm-10 col-10 col-lg-6">
            <h1 class="card-title">Upload image</h1>

            <div class="form-group mb-3 text-center">
              <!--droped image preview-->
              <div class="custom-dropzone" ngx-dropzone [accept]="'image/jpeg,image/jpg,image/png,image/gif'"
                (change)="onSelect($event)" >
                <ngx-dropzone-label>
                  <div>
                    <h2>Drop image here or press to select</h2>
                  </div>
                </ngx-dropzone-label>
                <ngx-dropzone-image-preview ngProjectAs="ngx-dropzone-preview" *ngFor="let f of files" [file]="f"
                  [removable]="true" (removed)="onRemove(f)">
                  <ngx-dropzone-label style="position:relative; padding-left: 10px;"><span> &nbsp; &nbsp; </span> {{ f.name }} ({{ f.type }})</ngx-dropzone-label>
                </ngx-dropzone-image-preview>
              </div>

              <!--droped image preview-->
            </div>

            <div class="form-group mb-3">
              <div class="text-center">
                <button (click)="onSubmit()"  class="btn btn-info" [disabled]="!imageValid">Submit</button>
              </div>
            </div>

            <!-- Shareable short link of  uploaded file -->
            <div class="container text-center jumbotron" *ngIf="shortLink">
              <h2> Visit Here</h2>
              <a href="{{shortLink}}">{{shortLink}}</a>
            </div>

            <!--Flag variable is used here-->
            <div class="mb-3 text-center text-danger" *ngIf="loading">
              <h3>Loading ...</h3>
            </div>
          </div>
        </div>

      </div>
    </div>

  </div>
</ng-container>



<!-- <section class="progress-bar" [hidden]="hideprogressBar">
  <mat-progress-bar color="primary" mode="determinate" [value]="percentDone">
  </mat-progress-bar>
</section>
<mat-card>
  <mat-card-title>File Uploader</mat-card-title>
  <mat-card-content>
      <mat-form-field class="full-width" appearance="outline">
          <mat-label>name</mat-label>
          <ng-template #newFile>
              <mat-label>Choose file</mat-label>
          </ng-template>
          <input matInput disabled>
          <button mat-icon-button matSuffix (click)="fileInput.click()">
              <mat-icon>attach_file</mat-icon>
          </button>
          <input hidden (change)="onSelectFile($event)" #fileInput name="uploadfile" type="file" id="file">
      </mat-form-field>
  </mat-card-content>
  <mat-card-actions>
      <button mat-raised-button color="primary" (click)="onUploadClick()">Upload</button>
  </mat-card-actions>
</mat-card>  -->

// .NET 7

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using NWIWasteWebAPI.Repositories.IRepository;
using NWIWasteWebAPI.Repositories.Models.BlobStorage;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace NWIWasteWebAPI.System.API.Controllers
{
 
    [ApiController]
    public class BlobStorageController : ControllerBase
    {
        private readonly IBlobRepository _blobRepository;

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

        [HttpGet("api/blob/{url}")]
        public async Task<IActionResult> GetBlobFile(string url)
        {
            BlobObject result = await _blobRepository.GetBlobFile(url);

            return File(result.Content, result.ContentType);
        }


        [HttpPost]
        [Route("api/blob/upload/file")]
        public async Task<IActionResult> UploadBlobFile(BlobContentModel model)
        {
            // "C:\\Users\\tset\\Pictures\\a.png
            var result = await _blobRepository.UploadBlobFile(model.FileName, model.FilePath);
            return Ok(result);
        }

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

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

            }

            return BadRequest();
        }

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

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

    public class BlobImageModel
    {
        public string FileName { get; set; }
        public string Image { get; set; }
    }
    
    public class BlobImageModel
    {
        public string FileName { get; set; }
        public string Image { get; set; }
    }
    
    public class BlobObject
    {
        public Stream Content { get; set; }
        public string ContentType { get; set; }
    }
// Some code

using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs;
using NWIWasteWebAPI.Repositories.Models.BlobStorage;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System;
using NWIWasteWebAPI.Repositories.IRepository;
using System.Linq;
using Microsoft.Extensions.Configuration;

namespace Repositories.Repository
{
    public class BlobRepository : IBlobRepository
    {
        private readonly BlobServiceClient _blobServiceClient;
        private BlobContainerClient client;
        private IConfiguration _configuration { get; }
        public static readonly List<string> ImageExtensions = new List<string> { ".JPG", ".JPEG", ".PNG" };

        public BlobRepository(BlobServiceClient blobServiceClient, IConfiguration iConfig)
        {
            _blobServiceClient = blobServiceClient;
            _configuration = iConfig;
            var blobContainer = iConfig.GetSection("BlobContainer").Value;
            client = _blobServiceClient.GetBlobContainerClient(blobContainer);   /////// Container name
        }
        public async void DeleteBlob(string url)
        {
            var fileName = new Uri(url).Segments.LastOrDefault();
            var blobClient = client.GetBlobClient(fileName);
            await blobClient.DeleteIfExistsAsync();
        }

        public async Task<BlobObject> GetBlobFile(string url)
        {
            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();

                    if (ImageExtensions.Contains(Path.GetExtension(fileName.ToUpperInvariant())))
                    {
                        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()
        {
            List<string> lst = new List<string>();

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

            return lst;
        }

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

            return blobClient.Uri.AbsoluteUri;
        }

        public async Task<string> UploadBlobImage(string fileName, string image)
        {
            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);
            }

            return blobClient.Uri.AbsoluteUri;
        }
    }
}

🪤
https://www.base64encoder.io/image-to-base64-converter/