An open API service indexing awesome lists of open source software.

https://github.com/mteheran/blazor-file-alibabacloud

This is a repositoty about how to manage file in blazor and how to use alibaba cloud to store files
https://github.com/mteheran/blazor-file-alibabacloud

Last synced: 3 months ago
JSON representation

This is a repositoty about how to manage file in blazor and how to use alibaba cloud to store files

Awesome Lists containing this project

README

          

## Blazor file management wth Alibaba cloud
In this repository you will find a complete guide to manage file in blazor and save files in alibaba cloud OSS

First, we have to create a new component and add the InputFile

```csharp

```

You can add a multiple file selection using "multiple" tag

```csharp

```

You must implement the OnChange method to get all the information about the file selected
```csharp
IBrowserFile file;
public async Task OnInputFileChange(InputFileChangeEventArgs e)
{
file = e.File;
}
```

You can read and show the properties from the IBrowserFile

```html


@file?.Name


@file?.ContentType


@(file?.Size != null ? file?.Size/1024 + " KBs" : "")


@file?.LastModified



```

Using Regex we can validate the file extension

```csharp
IBrowserFile file;
public async Task OnInputFileChange(InputFileChangeEventArgs e)
{

Regex regex = new Regex(".+\\.csv", RegexOptions.Compiled);
if (regex.IsMatch(e.File))
{
file = e.File;
}
}
```

Using "attributes" you can set HTML attributes to the control and indicate the extension file accepted

```csharp

Dictionary browseattributes = new Dictionary()
{
{ "accept", ".csv"} //accept online csv
};

```

You can use memory stream to read all the information from the file

```csharp
IBrowserFile file;
public async Task OnInputFileChange(InputFileChangeEventArgs e)
{
Regex regex = new Regex(".+\\.csv", RegexOptions.Compiled);
if (regex.IsMatch(e.File))
{
file = e.File;
var stream = file.OpenReadStream();
var csv = new List();
MemoryStream ms = new MemoryStream();
await stream.CopyToAsync(ms);
stream.Close();
var outputFileString = System.Text.Encoding.UTF8.GetString(ms.ToArray());

foreach (var item in outputFileString.Split(Environment.NewLine))
{
csv.Add(SplitCSV(item.ToString()));
}
}
}

private string[] SplitCSV(string input)
{
//Excludes commas within quotes
Regex csvSplit = new Regex("(?:^|,)(\"(?:[^\"]+|\"\")*\"|[^,]*)", RegexOptions.Compiled);
List list = new List();
string curr = null;
foreach (Match match in csvSplit.Matches(input))
{
curr = match.Value;
if (0 == curr.Length) list.Add("");
list.Add(curr.TrimStart(','));
}

return list.ToArray();
}
```

You can show the information of this file reading the first columns as header
and the rest of the rows are data

```csharp
@if(csvData.Count() > 0)
{



@foreach (var columnHeader in csvData[0])
{
@columnHeader
}



@foreach (var row in csvData.Skip(1))
{

@foreach (var item in row)
{
@item
}

}


}

public async Task OnInputFileChange(InputFileChangeEventArgs e)
{
file = e.File;
Regex regex = new Regex(".+\\.csv", RegexOptions.Compiled);
if (regex.IsMatch(file.Name))
{
var stream = file.OpenReadStream();
MemoryStream ms = new MemoryStream();
await stream.CopyToAsync(ms);
stream.Close();
var outputFileString = System.Text.Encoding.UTF8.GetString(ms.ToArray());
ReadAndShowFileInfo(outputFileString);
}
}

private void ReadAndShowFileInfo(string FileData)
{
foreach (var item in FileData.Split(Environment.NewLine))
{
csvData.Add(SplitCSV(item.ToString()));
}
}
```

### AlibabaCloud storage

AlibabaCloudStorageService is used to save and get information for a specifict container in AlibabaCloud object storage service

```csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using shared;
using Aliyun.OSS;
using Aliyun.OSS.Common;

namespace api.Services
{
public class AlibabaCloudStorageService : IAlibabaCloudStorageService
{
private readonly IConfiguration Configuration;
private readonly string bucketName = "mteheranst1";
private readonly string accessKeyId = "";
private readonly string accessKeySecret = "";
private readonly string endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
public AlibabaCloudStorageService(IConfiguration configuration)
{
Configuration = configuration;
accessKeyId = Configuration["AccessKeyId"];
accessKeySecret = Configuration["AccessKeySecret"];
endpoint = Configuration["Endpoint"];
}
public async Task SaveFileAsync(BlazorFile file)
{
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);

client.PutObject(bucketName, file.FileName, new MemoryStream(file.FileInfo));
}

public async Task> GetFiles()
{
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);

ObjectListing objects = client.ListObjects(bucketName);

List list = new List();

foreach(var item in objects.ObjectSummaries)
{
var newBlazorFile = new BlazorFile() { FileName = item.Key };
list.Add(newBlazorFile);
}

return list;
}

public async Task GetInfoFile(string fileName)
{

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);

var objectinfo = client.GetObject(bucketName, fileName);

MemoryStream ms = new MemoryStream();
await objectinfo.Content.CopyToAsync(ms);

var newBlazorFile = new BlazorFile() { FileName = objectinfo.Key, FileInfo = ms.ToArray() };

return newBlazorFile;
}

}

public interface IAlibabaCloudStorageService
{
Task SaveFileAsync(BlazorFile file);
Task> GetFiles();
Task GetInfoFile(string fileName);
}
}
```

You can set up this dependency on en Startup.cs file

```csharp
services.AddScoped();
```

Expose the method using the FileController.cs

```csharp
[ApiController]
[Route("[controller]")]
public class FileController : ControllerBase
{
private readonly ILogger _logger;
private readonly IAlibabaCloudStorageService _alibabaCloudFile;

public FileController(ILogger logger, IAlibabaCloudStorageService alibabaCloud)
{
_logger = logger;
_alibabaCloudFile = alibabaCloud;
}

[HttpGet]
public async Task> Get()
{
_logger.LogDebug("Gettings files...");
return await _alibabaCloudFile.GetFiles();
}

[HttpGet("{id}")]
public async Task Get(string id)
{
_logger.LogDebug("Gettings files...");
return await _alibabaCloudFile.GetInfoFile(id);
}

[HttpPost]
public IActionResult Post([FromBody] BlazorFile file)
{
_logger.LogDebug("Saving file...");
_alibabaCloudFile.SaveFileAsync(file);

_logger.LogDebug("File saved!");

return Ok();
}
}
```