Blazor wasm: IBrowser resize file after selection

Today’s progress on my webapp.
Working on adding a feature to attach one image to each complete ToDo item.
This way, you could look back and get a glimpse of your memory be it eating or doing some sort of activity.
I’m setting an upload limit of 16mb because my file storage approach is directly storing into Binary with Mongodb.  MongoDB only supports a max of 16megs per Binary.  You could upload bigger files if you use MongoDB’s GridFS.  Besides, I don’t think a photo taken with your smartphone will exceed 16megs anytime soon.

    public async Task HandleFileSelected(InputFileChangeEventArgs e)
    {
        isDisabled = true;
        selectedFile = e.File;

        // Resize the selected image
        resizedFile = await  selectedFile.RequestImageFileAsync(selectedFile.ContentType, 960, 540);

        // Save updated image to byte
        buffer = new byte[resizedFile.Size];

        // Update resizedFile's stream with buffer
        await resizedFile.OpenReadStream().ReadAsync(buffer);

        // Force UI update
        await InvokeAsync(StateHasChanged);
    }


    async void SaveItem()
    {
        if (selectedFile != null)
        {
            if (selectedFile.Size < maxFileSize)
            {

                var ms = new MemoryStream();
                todoItem.FileName = selectedFile.Name;
                await resizedFile.OpenReadStream(maxAllowedSize: 1024 * 1024 * 16).CopyToAsync(ms);
                todoItem.BinFile = ms.ToArray();
            }
            else
            {
                // Alert if file exceeds the limit
                await Swal.FireAsync("ファイルが大きすぎます(最大16mb)", "");
                return;
            }
        }

Leave a Reply

Your email address will not be published. Required fields are marked *