SteveSandersonMS / BlazorInputFile

A file input component for Blazor applications
250 stars 75 forks source link

How to upload multiple files on form submit? #36

Open bdfin opened 4 years ago

bdfin commented 4 years ago

First of all, thanks for your effort on this component.

I'm trying to upload multiple files on a form submit to Azure blob storage. Everything works perfectly if only one file is submitted but more than one causes this error: Microsoft.JSInterop.JSException: There is no file with ID 1. The file list may have changed Error: There is no file with ID 1. The file list may have changed at getFileById (https://localhost:5010/_content/BlazorInputFile/inputfile.js:116:19)

However I can see for sure that all files exist as they should in the list with the correct ids.

Here is my handle change and onsubmit:

`private void HandleChangeSelected(IFileListEntry[] files) { FileValidationMessage = string.Empty;

        IFileListEntry file = files.FirstOrDefault();

        if (UploadIsValid(file))
        {
            Files.Add(file);
        }
    }

    private async Task HandleValidSubmitAsync()
    {
        await AdvertService.CreateAdvertAsync(Advert);

        foreach (IFileListEntry file in Files)
        {
            await FileService.UploadImageAsync(file, Advert.Id, Vendor.Id);
        }
    }`

The error is thrown reading on the ReadAllAsync() method. Any ideas?

vantascloud commented 4 years ago

ok, for me, this turned out to be something silly, I was getting this error because InputFile tag was inside an if statement when a property of IFileListEntry[] had a zero count, and when it was greater than zero it was effectively destroying the InputFile tag and thus the file input elements. I moved the InputFile tag outside the if statement and it worked.

Jarrich commented 3 years ago

Did you ever manage to find the root cause, @bdfin ?

bdfin commented 3 years ago

Did you ever manage to find the root cause, @bdfin ?

No I ended up using a different soloution. This has actually been brought into the standard Blazor edit form components now so I'm wondering if it was fixed before release? Not sure though as I haven't tested.

valentasm1 commented 3 years ago

I have this very bad solution where i load all file to byte[] and then upload on submit. How achieve scenario where use select couple files one by one and the upload them un submit?

private List<byte[]> _addedFiles = new List<byte[]>();
private async Task SingleUpload(InputFileChangeEventArgs arg)
{
    long maxFileSize = 1024 * 1024 * 15;//15MB
    var data = arg.File.OpenReadStream(maxFileSize);
    using var memoryString = new MemoryStream();
    await data.CopyToAsync(memoryString);

    _addedFiles.Add(memoryString.GetBuffer());  
}