public void File_ThrowsIfMultipleFiles()
    {
        var instance = new InputFileChangeEventArgs(new[] { new BrowserFile(), new BrowserFile() });
        var ex       = Assert.Throws <InvalidOperationException>(() => instance.File);

        Assert.StartsWith("More than one file was supplied", ex.Message);
    }
    public void File_CanSupplySingle()
    {
        var file     = new BrowserFile();
        var instance = new InputFileChangeEventArgs(new[] { file });

        Assert.Same(file, instance.File);
    }
    public void File_ThrowsIfZeroFiles()
    {
        var instance = new InputFileChangeEventArgs(Array.Empty <IBrowserFile>());
        var ex       = Assert.Throws <InvalidOperationException>(() => instance.File);

        Assert.StartsWith("No file was supplied", ex.Message);
    }
Exemplo n.º 4
0
        private async Task ImportHardwareAsync(InputFileChangeEventArgs e)
        {
            if (!e.File.ContentType.Equals("text/xml", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var buffer = new byte[e.File.Size];

            using (var stream = e.File.OpenReadStream())
            {
                await stream.ReadAsync(buffer);
            }

            var file = new FileModel
            {
                FileName    = e.File.Name,
                ContentType = e.File.ContentType,
                Content     = buffer,
                Size        = e.File.Size
            };

            await HttpClient.PostJsonAsync($"/api/hardware/import/{Id}", file);

            Contract = await HttpClient.GetFromJsonAsync <ContractDetailVm>($"api/contract/{Id}");
        }
    /// <summary>
    ///
    /// </summary>
    /// <param name="args"></param>
    /// <returns></returns>
    protected override async Task OnFileChange(InputFileChangeEventArgs args)
    {
        CurrentFile = new UploadFile()
        {
            OriginFileName = args.File.Name,
            Size           = args.File.Size,
            File           = args.File,
            Uploaded       = false
        };
        CurrentFile.ValidateId = $"{Id}_{CurrentFile.GetHashCode()}";

        if (IsSingle)
        {
            // 单图片模式
            DefaultFileList?.Clear();
            UploadFiles.Clear();
        }

        UploadFiles.Add(CurrentFile);

        await base.OnFileChange(args);

        // ValidateFile 后 IsValid 才有值
        CurrentFile.IsValid = IsValid;

        if (OnChange != null)
        {
            await OnChange(CurrentFile);
        }
        else
        {
            await CurrentFile.RequestBase64ImageFileAsync(CurrentFile.File.ContentType, 320, 240);
        }
    }
Exemplo n.º 6
0
        protected ImageConverter _imageConverter;// = new ImageConverter();
        protected async Task OnInputFileChange(InputFileChangeEventArgs e)
        {
            var maxAllowedFiles = 1;
            var format          = "image/png";

            if (e.GetMultipleFiles(maxAllowedFiles).Count > maxAllowedFiles)
            {
                Message = "max Allowed Files are 5"; return;
            }
            foreach (var imageFile in e.GetMultipleFiles(maxAllowedFiles))
            {
                var resizedImageFile = await imageFile.RequestImageFileAsync(format, 100, 100);

                var buffer = new byte[resizedImageFile.Size];
                await resizedImageFile.OpenReadStream().ReadAsync(buffer);

                var imageDataUrl = $"data:{format};base64,{Convert.ToBase64String(buffer)}";
                if (imageDataUrl != null)
                {
                    imageDataUrls.Clear();
                    imageDataUrls.Add(imageDataUrl);
                }
                LineItemEditModel.Receipt = buffer;
                //var image = resizedImageFile.OptimizeImageSize(700, 700);
            }
        }
Exemplo n.º 7
0
        private async Task LoadFilesAsync(InputFileChangeEventArgs e)
        {
            if (e.FileCount > 1)
            {
                var files = e.GetMultipleFiles();
                var tasks = new List <Task>();
                foreach (var file in files)
                {
                    Logger.LogInformation($"uploading multiple files: {file.Name}");
                    tasks.Add(ChatViewModel.SendFileAsync(new File
                    {
                        Name        = file.Name,
                        Size        = (ulong)file.Size,
                        ContentType = file.ContentType
                    }, file.OpenReadStream(maxAllowedSize: file.Size)));
                }

                await Task.WhenAll(tasks);
            }
            else
            {
                var file = e.File;
                Logger.LogInformation($"uploading file: {file.Name}");
                await ChatViewModel.SendFileAsync(new File
                {
                    Name        = file.Name,
                    Size        = (ulong)file.Size,
                    ContentType = file.ContentType,
                }, file.OpenReadStream(maxAllowedSize: file.Size));
            }
        }
Exemplo n.º 8
0
        private async Task ProcessFile(InputFileChangeEventArgs e)
        {
            if (e.FileCount == 0)
            {
                return;
            }

            try
            {
                fileContent = "";

                // Maximum of 10 files per upload
                foreach (var file in e.GetMultipleFiles(10))
                {
                    // Maximum 10 MB file upload
                    using var reader = new StreamReader(file.OpenReadStream(10 * 1000 * 1024));
                    fileContent     += await reader.ReadToEndAsync() + Environment.NewLine;
                }

                canImportFile = true;
                await InvokeAsync(StateHasChanged);
            }
            catch (Exception ex)
            {
                await js.AlertException(ex);
            }
        }
Exemplo n.º 9
0
        async Task OnInputFileChange(InputFileChangeEventArgs e)
        {
            var             files = e.GetMultipleFiles(1);
            var             file  = files.FirstOrDefault();
            List <ToDoList> todosImported;

            byte[] result;
            using (var reader = file.OpenReadStream())
            {
                try
                {
                    result = new byte[reader.Length];
                    await reader.ReadAsync(result, 0, ( int )reader.Length);

                    var text = System.Text.Encoding.ASCII.GetString(result);
                    todosImported = JsonConvert.DeserializeObject <List <ToDoList> >(text);
                    if (todosImported.Count > 0)
                    {
                        foreach (var todo in todosImported)
                        {
                            todos.Add(todo);
                        }
                    }
                }
                catch (Exception exception)
                {
                    message = exception.Message;
                }
            }
        }
 private void OnInputFileChange(InputFileChangeEventArgs e)
 {
     BusyOverlayService.SetBusyState(BusyEnum.Busy);
     File = e.File;
     this.StateHasChanged();
     BusyOverlayService.SetBusyState(BusyEnum.NotBusy);
 }
    public void GetMultipleFiles_CanSupplyFiles()
    {
        var files    = new[] { new BrowserFile(), new BrowserFile() };
        var instance = new InputFileChangeEventArgs(files);

        Assert.Same(files, instance.GetMultipleFiles());
    }
        //async Task SaveAsUTF8(string filename, string content)
        //{
        //    byte[] data = Encoding.UTF8.GetBytes(content);
        //    await jsRuntime.InvokeAsync<object>("saveAsFile", filename, Convert.ToBase64String(data));
        //}

        async Task ImportNotes(InputFileChangeEventArgs e)
        {
            int count = e.FileCount;

            long maxId = DataService.GoalList.Any() ? DataService.GoalList.Max(g => g.Id) : 0;

            List <Goal> goalList = new List <Goal>();

            foreach (IBrowserFile browserFile in e.GetMultipleFiles(count))
            {
                string name = browserFile.Name;

                if (!name.EndsWith(".md"))
                {
                    continue;
                }

                Stream stream = browserFile.OpenReadStream();

                using StreamReader streamReader = new StreamReader(stream);

                string text = await streamReader.ReadToEndAsync();

                Goal goal = new Goal
                {
                    Id          = ++maxId,
                    CategoryId  = DataService.RootCategory.Id,
                    Description = name[0..^ 3],
Exemplo n.º 13
0
        async Task HandleFileSelected(InputFileChangeEventArgs e)
        {
            using var content = new MultipartFormDataContent();
            foreach (var file in e.GetMultipleFiles(e.FileCount))
            {
                content.Add(new StreamContent(file.OpenReadStream()), "files", file.Name);
            }

            var httpClient = _httpClientFactory.CreateClient("oidc");

            using var response = await httpClient.PostAsync($"{httpClient.BaseAddress}/import", content).ConfigureAwait(false);

            var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            if (!response.IsSuccessStatusCode)
            {
                _error = new MarkupString($"{response.StatusCode}<br/>{responseContent.Replace("\n","<br/>")}");
            }
            else
            {
                _result = JsonSerializer.Deserialize <ImportResult>(responseContent, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                });
            }

            await InvokeAsync(StateHasChanged).ConfigureAwait(false);
        }
        private async Task OnInputFileMetadataChange(
            InputFileChangeEventArgs e)
        {
            isLoading = true;

            if (e.FileCount != 1)
            {
                return;
            }

            try
            {
                // TODO IoC?
                MetadataReader metadataReader =
                    new MetadataReader(
                        new MetadataParser(
                            new MetadataConverter()));

                this.Metadata =
                    await metadataReader.ReadAsync(e.File.OpenReadStream());

                await MetadataChanged.InvokeAsync(this.Metadata);
            }
            catch
            {
                // TODO: Indicate error state
            }
            finally
            {
                isLoading = false;
            }
        }
Exemplo n.º 15
0
        async Task LoadFiles(InputFileChangeEventArgs e)
        {
            this.isLoading    = true;
            this.errorMessage = string.Empty;
            this.saveMassage  = string.Empty;

            try
            {
                foreach (var file in e.GetMultipleFiles(1))
                {
                    StateHasChanged();
                    var buffers = new byte[file.Size];
                    await file.OpenReadStream().ReadAsync(buffers);

                    this.uploadFile.FileName     = file.Name;
                    this.uploadFile.ContentType  = file.ContentType;
                    this.uploadFile.Size         = file.Size;
                    this.uploadFile.LastModified = file.LastModified;
                    this.uploadFile.Content      = buffers;
                }
            }
            catch (Exception ex)
            {
                this.errorMessage = ex.Message;
            }
            finally
            {
                this.isLoading = false;
            }
        }
        async Task OnInputFileChange(InputFileChangeEventArgs e)
        {
            var path = Path.Combine(WebHostEnvironment.WebRootPath, imgPath);
            await FileStorageService.UploadFile(path, e.File);

            Institution.Logo = e.File.Name;
        }
Exemplo n.º 17
0
        private async Task OnFileChange(InputFileChangeEventArgs args)
        {
            var files = new List <UploadFile>();

            if (IsMultiple || Style == UploadStyle.UploadFolder)
            {
                files.AddRange(args.GetMultipleFiles(MaxFileCount).Select(f => new UploadFile()
                {
                    OriginFileName = f.Name,
                    Size           = f.Size,
                    File           = f,
                    UpdateCallback = Update
                }));
            }
            else
            {
                var file = new UploadFile()
                {
                    OriginFileName = args.File.Name,
                    Size           = args.File.Size,
                    File           = args.File,
                    UpdateCallback = Update
                };
                files.Add(file);
            }

            UploadFiles.AddRange(files);

            if (OnChange != null)
            {
                await OnChange(files);
            }
        }
Exemplo n.º 18
0
        private async Task UploadFiles(InputFileChangeEventArgs e)
        {
            file = e.File;
            if (file != null)
            {
                var format    = "image/png";
                var imageFile = await e.File.RequestImageFileAsync(format, 250, 250);

                var buffer = new byte[imageFile.Size];
                await imageFile.OpenReadStream().ReadAsync(buffer);

                ImageDataUrl = $"data:{format};base64,{Convert.ToBase64String(buffer)}";
                var request = new UpdateProfilePictureRequest()
                {
                    ProfilePictureDataUrl = ImageDataUrl
                };
                var result = await _accountManager.UpdateProfilePictureAsync(request, UserId);

                if (result.Succeeded)
                {
                    _navigationManager.NavigateTo("/account", true);
                }
                else
                {
                    foreach (var error in result.Messages)
                    {
                        _snackBar.Add(error, Severity.Success);
                    }
                }
            }
        }
Exemplo n.º 19
0
        private async Task OnFileInputChanged(InputFileChangeEventArgs evt)
        {
            var file = evt.File;

            if (file is null)
            {
                _input.Contents      = ReadOnlyMemory <byte> .Empty;
                _input.StatusMessage = "Please select a file to upload...";
            }
            else if (file.Size > MAX_FILESIZE)
            {
                _input.Contents      = ReadOnlyMemory <byte> .Empty;
                _input.StatusMessage = "File is too big...";
            }
            else
            {
                await using var ms = new MemoryStream();
                await file.OpenReadStream(MAX_FILESIZE).CopyToAsync(ms);

                _input.Contents = ms.ToArray();
                if (_input.Contents.IsEmpty)
                {
                    _input.StatusMessage = $"The file {file.Name} appears to be empty.";
                }
                else
                {
                    _input.StatusMessage = $"Loaded {file.Size} bytes from {file.Name}";
                }
            }
        }
Exemplo n.º 20
0
        protected async Task OnInputFileChange(InputFileChangeEventArgs e)
        {
            Model.Avatar = new Image();
            var imagesDataUrls = await ImageUploadProcessor.GetDataUrlsFromUploadedImagesAsync(e);

            Model.Avatar.Path = imagesDataUrls.First();
        }
        private async Task LoadContract(InputFileChangeEventArgs e)
        {
            FileLoader = true;
            StateHasChanged();

            FileName = e.File.Name;

            await using Stream fileStream = e.File.OpenReadStream();
            await using var memoryStream  = new MemoryStream();
            await fileStream.CopyToAsync(memoryStream);

            JsDataUri = $"data:{e.File.ContentType};base64,{Convert.ToBase64String(memoryStream.ToArray())}";

            try
            {
                ContractPackage = await JsRuntime.InvokeAsync <TonPackage>("getContactPackage", JsDataUri)
                                  .CatchJsExceptionAsync(ex => ToastService.ShowError(ex.Message));
            }
            catch (JSException)
            {
                JsDataUri = null;
                StateHasChanged();
                throw;
            }

            await Task.Delay(1000);

            FileLoader = false;
            ProgressCurrentStep++;
        }
Exemplo n.º 22
0
        public async Task OpenGraphItFile(InputFileChangeEventArgs e, bool overwrite)
        {
            Overwrite = overwrite;
            try
            {
                byte[]  temp;
                Options newOptions = new Options();
                using (var streamReader = new MemoryStream())
                {
                    await e.File.OpenReadStream().CopyToAsync(streamReader);

                    temp = streamReader.ToArray();
                }
                OpenPreference = false;
                string      graph   = DecodeAndInflate(temp);
                XmlDocument xmlData = new XmlDocument();
                xmlData.LoadXml(graph);
                if (Overwrite)
                {
                    Graph = new Graph();
                }
                Traverse(xmlData, NodeService.NextId(Graph.Nodes), EdgeService.NextId(Graph.Edges));
                await GraphChanged.InvokeAsync(Graph);

                if (Overwrite)
                {
                    await OptionsChanged.InvokeAsync(Options);
                }
            }
            catch (ObjectDisposedException)
            {
                ErrorOpening = true;
            }
        }
Exemplo n.º 23
0
        async Task LoadFiles(InputFileChangeEventArgs e)
        {
            var isLoading        = true;
            var exceptionMessage = string.Empty;

            try {
                foreach (var file in e.GetMultipleFiles(maxAllowedFiles))
                {
                    //using var reader =
                    //    new StreamReader(file.OpenReadStream());
                    using (var stream = new MemoryStream()) {
                        await file.OpenReadStream().CopyToAsync(stream);

                        stream.Position = 0;
                        InputFiles.Add(stream.ToArray());
                    }

                    //loadedFiles.Add(file, await reader.ReadToEndAsync());
                }
            } catch (Exception ex) {
                exceptionMessage = ex.Message;
            }

            isLoading = false;
        }
Exemplo n.º 24
0
        protected async Task HandleFileSelection(InputFileChangeEventArgs e)
        {
            file          = e.File;
            isFileChanged = true;
            if (file != null)
            {
                var ext = Path.GetExtension(file.Name);
                if (ext.Contains("jpg") || ext.Contains("png") || ext.Contains("jpeg") || ext.Contains("pdf"))
                {
                    msFile = file.OpenReadStream();

                    var resizedImageFile = await file.RequestImageFileAsync("image/png", 100, 100);

                    var buffer = new byte[resizedImageFile.Size];
                    await resizedImageFile.OpenReadStream().ReadAsync(buffer);

                    var imageBase64Data = Convert.ToBase64String(buffer);
                    imageDataURL      = string.Format("data:image/png;base64,{0}", imageBase64Data);
                    isInvalidFileType = false;
                }
                else
                {
                    isInvalidFileType = true;
                    imageDataURL      = string.Empty;
                }
            }
            else
            {
                isInvalidFileType = false;
            }
        }
        //Functions

        public async Task OninputFileChange(InputFileChangeEventArgs e)
        {
            var imagesFiles = e.GetMultipleFiles();
            var format      = "image/png";

            selectedImage = imagesFiles;

            int i = addImageDTOs.Count;

            addImageDTOs = new List <AddImageDTO>();

            foreach (var imageFile in imagesFiles)
            {
                var resizedImageFile = await imageFile.RequestImageFileAsync(format, 100, 100);

                var buffer = new byte[resizedImageFile.Size];
                await resizedImageFile.OpenReadStream().ReadAsync(buffer);

                var imageDataUrl = $"data:{format};base64,{Convert.ToBase64String(buffer)}";

                AddImageDTO dTO = new AddImageDTO
                {
                    imageDataUrl = imageDataUrl,
                    ProductImage = new ProductImage
                    {
                        ProductImagePosition = i,
                        Name = imageFile.Name
                    },
                };
                addImageDTOs.Add(dTO);
                i++;
            }
        }
        private async Task OnInputFileChange(InputFileChangeEventArgs e)
        {
            IsLoading            = true;
            this.ResponseMessage = $"Invoked: {e.FileCount} files";
            this.FileName        = e.File.Name;
            if (e.File != null)
            {
                int          maxSizeInMB  = (1024 * 1000) * 10; // 10MB
                var          fileStream   = e.File.OpenReadStream(maxAllowedSize: maxSizeInMB);
                MemoryStream memoryStream = new MemoryStream();
                await fileStream.CopyToAsync(memoryStream);

                var imageBase64 = Convert.ToBase64String(memoryStream.ToArray());
                this.ImageBase64 = imageBase64;
                StateHasChanged();
                DescribeImageRequestModel model = new DescribeImageRequestModel()
                {
                    ImageBase64 = imageBase64
                };
                string requestUrl = "api/AudibleComputerVision/DescribeImage";
                var    response   = await Http.PostAsJsonAsync <DescribeImageRequestModel>(requestUrl, model);

                if (response.IsSuccessStatusCode)
                {
                    this.AudioBase64 = await response.Content.ReadAsStringAsync();

                    StateHasChanged();
                }
                this.ResponseMessage = await response.Content.ReadAsStringAsync();
            }
            IsLoading = false;
        }
        private async Task UploadFiles(InputFileChangeEventArgs e)
        {
            file = e.File;
            if (file != null)
            {
                var extension = Path.GetExtension(file.Name);
                var fileName  = $"{UserId}-{Guid.NewGuid()}{extension}";
                var format    = "image/png";
                var imageFile = await e.File.RequestImageFileAsync(format, 400, 400);

                var buffer = new byte[imageFile.Size];
                await imageFile.OpenReadStream().ReadAsync(buffer);

                var request = new UpdateProfilePictureRequest()
                {
                    Data = buffer, FileName = fileName, Extension = extension, UploadType = Application.Enums.UploadType.ProfilePicture
                };
                var result = await _accountManager.UpdateProfilePictureAsync(request, UserId);

                if (result.Succeeded)
                {
                    await _localStorage.SetItemAsync("userImageURL", result.Data);

                    _navigationManager.NavigateTo("/account", true);
                }
                else
                {
                    foreach (var error in result.Messages)
                    {
                        _snackBar.Add(localizer[error], Severity.Error);
                    }
                }
            }
        }
Exemplo n.º 28
0
        public async Task SetCoverImage(InputFileChangeEventArgs e, ICoverImageable coverImageable)
        {
            if (coverImageable == null)
            {
                return;
            }

            var maxAllowedFiles = 1;
            var format          = "image/png";

            foreach (var imageFile in e.GetMultipleFiles(maxAllowedFiles))
            {
                var resizedImageFile = await imageFile.RequestImageFileAsync(Format,
                                                                             500, 500);

                var buffer = new byte[resizedImageFile.Size];
                await resizedImageFile.OpenReadStream().ReadAsync(buffer);

                var imageDataUrl = $"data:{format};base64,{Convert.ToBase64String(buffer)}";
                if (coverImageable.Blob == null)
                {
                    coverImageable.Blob = new Blob();
                }
                coverImageable.Blob.Data = imageDataUrl;
            }
        }
Exemplo n.º 29
0
        // Called when a new file is uploaded
        protected async Task OnChange(InputFileChangeEventArgs e)
        {
            using var stream = e.File.OpenReadStream();
            using var ms     = new MemoryStream();
            await stream.CopyToAsync(ms);

            string content = System.Text.Encoding.UTF8.GetString(ms.ToArray());

            var doc  = new XmlDocument();
            var args = new UploadEventArgs();

            try
            {
                doc.LoadXml(content);
            }
            catch (XmlException)
            {
                args.Errors = "Invalid XML data found in uploaded SVG file.";
                await Upload.InvokeAsync(args);

                return;
            }

            // Search for the script
            StringWriter swScript = new();

            foreach (XmlNode node in doc.DocumentElement.GetElementsByTagName("sc:script"))
            {
                if (node.ChildNodes.Count == 1 && node.ChildNodes[0] is XmlCDataSection cdata)
                {
                    swScript.WriteLine(cdata.Data);
                }
                else
                {
                    swScript.WriteLine(node.InnerText);
                }
            }

            // Search for the style
            StringWriter swStyle = new();

            foreach (XmlNode node in doc.DocumentElement.GetElementsByTagName("style"))
            {
                swStyle.WriteLine(node.InnerText);
            }

            // Call the event
            args.Script = swScript.ToString();
            args.Style  = swStyle.ToString();
            if (args.Script.Length == 0)
            {
                args.Errors = "No SimpleCircuit script metadata found in uploaded SVG file.";
            }
            else if (args.Style.Length == 0)
            {
                args.Warnings = "No styling information found in uploaded SVG file.";
            }
            await Upload.InvokeAsync(args);
        }
    public void GetMultipleFiles_ThrowsIfTooManyFiles()
    {
        var files    = new[] { new BrowserFile(), new BrowserFile() };
        var instance = new InputFileChangeEventArgs(files);
        var ex       = Assert.Throws <InvalidOperationException>(() => instance.GetMultipleFiles(1));

        Assert.Equal($"The maximum number of files accepted is 1, but 2 were supplied.", ex.Message);
    }