Files
2021-12-07 18:28:04 +01:00

98 lines
3.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using System.Net.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.Web.Virtualization;
using Microsoft.JSInterop;
using RuleManager.UI;
using RuleManager.UI.Shared;
using System.Linq;
using System.Net.Http.Headers;
using System.Text.Json;
using Microsoft.Extensions.Logging;
namespace RuleManager.UI.Pages
{
public partial class FileUpload2
{
[Inject]
private ILogger<FileUpload2>? Logger { get; set; }
private List<File> files = new();
private List<UploadResult> uploadResults = new();
private int maxAllowedFiles = 3;
private bool shouldRender;
protected override bool ShouldRender() => shouldRender;
private async Task OnInputFileChange(InputFileChangeEventArgs e)
{
shouldRender = false;
long maxFileSize = 1024 * 1024 * 15;
var upload = false;
using var content = new MultipartFormDataContent();
foreach (var file in e.GetMultipleFiles(maxAllowedFiles))
{
if (uploadResults.SingleOrDefault(f => f.FileName == file.Name)is null)
{
try
{
var fileContent = new StreamContent(file.OpenReadStream(maxFileSize));
fileContent.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType);
files.Add(new()
{Name = file.Name});
content.Add(content: fileContent, name: "\"files\"", fileName: file.Name);
upload = true;
}
catch (Exception ex)
{
Logger.LogInformation("{FileName} not uploaded (Err: 6): {Message}", file.Name, ex.Message);
uploadResults.Add(new()
{FileName = file.Name, ErrorCode = 6, Uploaded = false});
}
}
}
if (upload)
{
var client = ClientFactory.CreateClient();
var response = await client.PostAsync("https://localhost:5001/Filesave", content);
if (response.IsSuccessStatusCode)
{
var options = new JsonSerializerOptions{PropertyNameCaseInsensitive = true, };
using var responseStream = await response.Content.ReadAsStreamAsync();
var newUploadResults = await JsonSerializer.DeserializeAsync<IList<UploadResult>>(responseStream, options);
if (newUploadResults is not null)
{
uploadResults = uploadResults.Concat(newUploadResults).ToList();
}
}
}
shouldRender = true;
}
private static bool FileUpload(IList<UploadResult> uploadResults, string? fileName, ILogger<FileUpload2> logger, out UploadResult result)
{
result = uploadResults.SingleOrDefault(f => f.FileName == fileName) ?? new();
if (!result.Uploaded)
{
logger.LogInformation("{FileName} not uploaded (Err: 5)", fileName);
result.ErrorCode = 5;
}
return result.Uploaded;
}
private class File
{
public string? Name { get; set; }
}
}
}