Coder Social home page Coder Social logo

blazorinputfile's Introduction

blazorinputfile's People

Contributors

ellested avatar stevesandersonms avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

blazorinputfile's Issues

Upload action of InputFile submits parent EditForm

Hi Steve, first, thank you for this great component!

I wrapped InputFile in a reusable component CustomInputFile that supports upload/download/delete functionality by calling methods on a back-end FileController, and notifies the parent component about changes through OnFileUploaded EventCallback.


@inject HttpClient HttpClient
@using System.IO
@using BlazorInputFile
@using TuServicioWebsite.Shared.Utils
@inject NavigationManager UriHelper

<InputFile OnChange="HandleFileSelected" UnmatchedParameters="UnmatchedParameters" />
@if (selectedFile != null)
{
    isLoading = selectedFile.Data.Position > 0;

<div class="file-row">
    <div>
        <h2>@selectedFile.Name</h2>
        Size: <strong>@savedFileSize</strong>;
        Last update: <strong>@selectedFile.LastModified.ToShortDateString()</strong>;
        Type: <strong>@selectedFile.Type</strong>
    </div>

    <!-- Upload button -->
    <button @onclick="() => LoadFile(selectedFile)" disabled="@isLoading">
        @if (!isLoading)
        {
            <span>Subir</span>
        }
        else
        {
            <span>Loaded @((100.0 * selectedFile.Data.Position / selectedFile.Size).ToString("0"))%</span>
        }
    </button>
    @if (isLoading && (savedFileId == Guid.Empty))
    {
        <button @onclick="() => ClearInputFileFields()">Delete</button>
    }
    @if (savedFileId != Guid.Empty)
    {
        <button @onclick="() => DownloadFile()">Download</button>
        <button @onclick="() => DeleteFile()">Delete</button>
    }
</div>
}

@code {

    IFileListEntry selectedFile;
    bool isLoading;
    [Parameter] public EventCallback<Tuple<Guid, string, string, string>> OnFileUploaded { get; set; }
    [Parameter(CaptureUnmatchedValues = true)] public Dictionary<string, object> UnmatchedParameters { get; set; }

    Guid savedFileId { get; set; } = Guid.Empty;
    string savedFileName { get; set; } = "";
    string savedFileType { get; set; } = "";
    string savedFileSize { get; set; } = "";

    void HandleFileSelected(IFileListEntry[] files)
    {
        selectedFile = files.FirstOrDefault();
    }

    async Task LoadFile(IFileListEntry file)
    {
        // So the UI updates to show progress
        file.OnDataRead += (sender, eventArgs) => InvokeAsync(StateHasChanged);

        // Load content into .NET memory stream
        // Alternatively it could be saved to disk, or parsed in memory, or similar
        var ms = new MemoryStream();
        await file.Data.CopyToAsync(ms);

        //Send file content to back-end
        var content = new MultipartFormDataContent {
                { new ByteArrayContent(ms.GetBuffer()), "\"upload\"", file.Name }
            };
        HttpResponseMessage response = await HttpClient.PostAsync("api/File/Upload", content);
        //Notify parent component
        string guidText = await response.Content.ReadAsStringAsync();
        savedFileId = new Guid(guidText);
        savedFileName = file.Name;
        savedFileSize = UiHelper.ConvertSizeInBytesToHumanReadableDescription(file.Size);
        savedFileType = file.Type;
        await OnFileUploaded.InvokeAsync(new Tuple<Guid, string, string, string>(savedFileId, savedFileName, savedFileType, savedFileSize));
    }

    async void DownloadFile()
    {
        if (savedFileId != Guid.Empty)
            UriHelper.NavigateTo($"api/File/Download/{savedFileId}", forceLoad: true);
    }

    async void DeleteFile()
    {
        if (savedFileId != Guid.Empty)
        {
            await HttpClient.PostJsonAsync($"api/File/Delete/{savedFileId}", savedFileId);
            await ClearInputFileFields();

        }
    }
    async Task ClearInputFileFields()
    {
        savedFileId = Guid.Empty;
        savedFileName = "";
        savedFileType = "";
        selectedFile = null;
        isLoading = false;
        await OnFileUploaded.InvokeAsync(new Tuple<Guid, string, string, string>(savedFileId, savedFileName, savedFileType, savedFileSize));
    }
}

When using it in EditForm of the parent .razor page, on finished upload, EditForm is also submitted. Here is the code of parent component:

<EditForm id="editFormDocumentation" Model="@pd" OnValidSubmit="@(async () => await CreateProjectDataModel())">
            <DataAnnotationsValidator />
            <ValidationSummary />
           <div class="form-group row">
                <label for="projectCode" class="col-form-label col-sm-4">Project code</label>
                <InputText id="projectCode" class="form-control col-sm-8" @bind-Value="@pd.ProjectCode" />
                <ValidationMessage For="@(() => pd.ProjectCode)" />
            </div>
            <div class="form-group row">
                <label for="projectName" class="col-form-label col-sm-4">Project name</label>
                <InputText id="projectName" class="form-control col-sm-8" @bind-Value="@pd.ProjectName" />
                <ValidationMessage For="@(() => pd.ProjectName)" />
            </div>
            <div class="form-group row">
                <label for="dbc" class="col-sm-4 col-form-label">DBC file</label>
                <div id="dbc" class="col-sm-8">
                    <CustomInputFile OnFileUploaded="@((args) => {
                                                       pd.DbcFileId = args.Item1;
                                                       pd.DbcFileName = args.Item2;
                                                       StateHasChanged();
                                                   })" />
                    <ValidationMessage For="@(() => pd.DbcFileId)" />
                </div>
            </div>
            <div class="form-group row">
                <label for="terms" class="col-sm-4 col-form-label">Reference terms</label>
                <div id="terms" class="col-sm-8">
                    <CustomInputFile OnFileUploaded="@((args) => {
                                                       pd.ReferenceTermsFileId = args.Item1;
                                                       pd.ReferenceTermsFileName = args.Item2;
                                                       StateHasChanged();
                                                   })" />
                    <ValidationMessage For="@(() => pd.ReferenceTermsFileId)" />
                </div>
            </div>
            <div class="form-group row">
                <div class="col-sm-4">
                    <input type="submit" class="btn btn-danger" @onclick="@Cancel" style="width:220px;" value="Cancel" />
                </div>
                <div class="col-sm-8">
                    <input type="submit" class="btn btn-success" @onclick="@SubmitData" style="width:220px;" value="Save" />
                </div>
            </div>
        </EditForm>

Code behind the parent page is very simple

    
    ProjectDataModel pd = new ProjectDataModel();
...
    private async Task SubmitData()
    {
        System.Console.WriteLine("Window 1: Data submitted.");
    }

    async Task CreateProjectDataModel()
    {
        if (pd != null && !string.IsNullOrEmpty(paramProjectCode))
        {
            await HttpClient.SendJsonAsync(HttpMethod.Put, "api/ProjectsData/Edit", pd);
        }
        else
        {
            pd = await HttpClient.SendJsonAsync<ProjectDataModel>(HttpMethod.Post, "api/ProjectsData/Create", pd);
        }
        UriHelper.NavigateTo("/Dashboard/fetch");
    }

    void Cancel()
    {
        UriHelper.NavigateTo("/Dashboard/fetch");
    }
public class ProjectDataModel
    {
        [Required]
        [Key]
        public string ProjectCode { get; set; }
        [Required]
        public string ProjectName { get; set; }
        public Guid DbcFileId { get; set; }
        public string DbcFileName {get; set; }
        public Guid ReferenceTermsFileId { get; set; }
        public string ReferenceTermsFileName { get; set; }
}

Because ProjectCode and ProjectName properties are specified, when I upload a file (in my case Dbc file), the validation passes and method CreateProjectDataModel gets called before I upload the second file, ReferenceTerms.

My question is, how do I make InputFile not to call CreateProjectDataModel of parent EditForm ? I still want to have validation on the file info(DbcFileId !=Guid.Empty or regex validation on file name).

File presence is not necessary for the EditForm model to be valid. File can be uploaded later, after saving ProjectDataModel.

Reset Stream back to the begining

I am trying to read a file back from the beginning. I've tried several solutions on the Web but they all crash with a: "Synchronous reads are not supported."
Any solution?
Thanks!

ToImageFile with quality

Would it be possible to have a implementation on the fly in order to be able to specify the quality of the output image file when calling IFileListEntry.ToImageFileAsync?
It'd be an awesome cherry on top of the cake!

Thanks in advance!

ReadRequest Struct throwing error

Hi Steve,

Thanks for making this component. The Nuget package works great, however when we try to use the source code in a project, we get the following error:

Could not load type 'ReadRequest' from assembly 'XXXX, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it contains an object field at offset 4 that is incorrectly aligned or overlapped by a non-object field.

Here's the struct:

[StructLayout(LayoutKind.Explicit)]
public struct ReadRequest
{
[FieldOffset(0)] public string InputFileElementReferenceId;
[FieldOffset(4)] public int FileId;
[FieldOffset(8)] public long SourceOffset;
[FieldOffset(16)] public byte[] Destination;
[FieldOffset(20)] public int DestinationOffset;
[FieldOffset(24)] public int MaxBytes;
}

Using:

  • Visual Studio 16.4.2 Preview 2
  • Dot Net Core 3.1
  • Blazor Server Side

Any ideas?

Thanks in advance.
Rod

CopyToAsync hangs in provided sample project

In the usage information blog post there is an example of a multiple file upload with this source code. In the blog post there is a gif demonstration which shows three files being asynchronously copied to a MemoryStream.

If you begin each copy to MemoryStream before any other files finish copying, this process works fine. However, if you call await file.Data.CopyToAsync(ms) after any other file has finished copying to MemoryStream, the copy hangs after getting ~500kB copied.

You can verify this by cloning the repo and running the sample program with the MultiFile.razor page. Select two or more files to upload, then click the Load button on one of them. Wait until that file is 100% loaded. Then click Load on another file. It will hang.

This is a problem for me because I have a form where 3 different files get selected, using 3 different <InputFile> components. The files begin uploading as soon as their selected, which involves reading the Stream in file.Data. If the user selects a 2nd or 3rd file after a file has finished uploading the newly selected file fails to upload. The program simply hangs.

I have been using files that are 3-50MB in size, which is what I expect the file size range to be in production.

Uploaded .zip Files are corrupted

Hey, I've been trying to upload a .zip file using Inputfile, but while the upload completes without a problem, I cannot open the .zip file afterwards. The file size after the upload is identical to the one before, so I'm not sure what the reason could be. Any ideas?

error on edge - Object doesn't support property or method 'toBlob'

Exception: Microsoft.JSInterop.JSException: Object doesn't support property or method 'toBlob'
TypeError: Object doesn't support property or method 'toBlob'
at Anonymous function (https://localhost:44306/_content/BlazorInputFile/inputfile.js:54:21)
at Promise (native code)
at Anonymous function (https://localhost:44306/_content/BlazorInputFile/inputfile.js:45:17)
at System.Threading.Tasks.ValueTask`1[TResult].get_Result () <0x3ae3268 + 0x0002c> in :0
at BlazorInputFile.InputFile.ConvertToImageFileAsync (BlazorInputFile.FileListEntryImpl file, System.String format, System.Int32 maxWidth, System.Int32 maxHeight) <0x3ada828 + 0x00134> in :0
at BlazorInputFile.FileListEntryImpl.ToImageFileAsync (System.String format, System.Int32 maxWidth, System.Int32 maxHeight) <0x3ad97c0 + 0x000ea> in :0
at VerusDate.Client.Pages.ProfileGallery.HandleFileSelected (BlazorInputFile.IFileListEntry[] files) <0x3acf040

License

Which license is BlazorInputFile using? It looks nice but without an unambiguous statement about the license we can't use it :|

IE not working

Blazor input file is not working in Internet Explorer.

With Version="0.2.0", it does not work at all, I got the following error:
image

With Version="0.1.0-preview-00002" and Version="0.1.0", I can open the file dialog and select a file, but after that I got the error:
SCRIPT5001: Number expected
inputfile.js (10,21)

I have app.UseStaticFiles(); in my Startup.cs file and it is working perfect in Chrome.

Upload files only on EditForm submit?

Currently BlazorInputFile automatically uploads files once a file was selected. I want to upload files only on a valid EditForm submit. How can that be done? Thanks!

How to upload multiple files on form submit?

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?

Bug when re-uploading a file

My application has a file validation step. When the validation fails, a new file has to be uploaded. Then, when I try to upload a new file using the same component, the stream doesn't update with the data of the new file. Any solutions to this? Thanks.

The maximum allowed size error when calling ReadAllSync

When calling ReadAllAsync I'm getting this error:

"The maximum allowed size is 1048576, but the supplied file is of length 1203571. Parameter fileListEntry"

The file size is 1,176,000 bytes.

What is the file size limit for BlazorInputFile?

Is there any way to load files this size?

Immidiately use Image

Hey Steve, I've been using your library and I think it's great!

I've been wanting to use it recently to immediately display an image on the page.

From what I've been reading I'd need to set src attribute on an tag to be :

"window.URL.createObjectURL(fileObj);"

Where fileObj is the file that is uploaded through the BlazorInputFile.

Do you have any idea to how I might reference the file object that is retrieved with BlazorInputFile ?

Could not find 'BlazorInputFile' in 'window'

For some reason, my server side blazor app no longer works with the BlazorInputFile package. When i attempt to upload a file using this, my chrome dev console is throwing an error.

[2020-03-18T20:31:14.001Z] Error: Microsoft.JSInterop.JSException: Could not find 'BlazorInputFile' in 'window'.
Error: Could not find 'BlazorInputFile' in 'window'.
at https://localhost/_framework/blazor.server.js:8:30748
at Array.forEach ()
at p (https://localhost/_framework/blazor.server.js:8:30709)
at https://localhost/_framework/blazor.server.js:8:31416
at new Promise ()
at e.beginInvokeJSFromDotNet (https://localhost/_framework/blazor.server.js:8:31390)
at https://localhost/_framework/blazor.server.js:1:19202
at Array.forEach ()
at e.invokeClientMethod (https://localhost/_framework/blazor.server.js:1:19173)
at e.processIncomingData (https://localhost/_framework/blazor.server.js:1:17165)
at Microsoft.JSInterop.JSRuntime.InvokeWithDefaultCancellation[T](String identifier, Object[] args)
at BlazorInputFile.InputFile.OnAfterRenderAsync(Boolean firstRender)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)

I have tried uninstalling and reinstalling the package, clearing nuget cache, rebuilding the project, all with no luck. I am not sure where to look..

I want InputFolder to pick a folder

Hello, I would like an inout folder tag to be able to just pick a folder location and store the location in a variable. I want this folder picker in the settings page. I don't want to do anything like upload files. I want to be able to present an editor that allows notes to be created and stored in this folder location that the user has picked.

ReadAsync into memory stream is extremely slow

Steve,

I set up the simple demo per your writeup. Loading a 15Mb file takes 55 seconds!
Your writeup says "...For client-side Blazor (WebAssembly), the data transfer speed is limited only by your CPU. You can load a 10 MB file into .NET memory almost instantly. On my machine, loading a 100 MB file into a .NET byte array takes about a second...."
Can you provide the sample code that accomplished this?

Add files multiple times, (show dialog a second time)

great control thanks for posting it.

using the multiple files example (MultiFile.razor) if you select one or more files all works well
but if you press the browse button a second time and select another file or files
when you call the "async Task LoadFile" method it get this error
"Microsoft.JSInterop.JSException: 'There is no file with ID 1. The file list may have changed"

This should be handled as often people want to add multiple files and then upload them, when they aren't in the same directory, or add another file after adding some initial ones.

I fixed this by modifying the javascript

in the init function
I change the line
elem._blazorFilesById = {};
to
if (typeof elem._blazorFilesById === 'undefined') {
elem._blazorFilesById = {};
}

some questions:

  1. Is this a good way to handle selecting files multiple times

  2. in the javascript after adding the file it calls
    Object.defineProperty(result, 'blob', { value: file });
    should there be a dispose for this or is it just handled by garbage collection when the page is no longer is scope
    the component implements the IDisposable, so should it call a javascript dispose method and clean these up

can't reset the stream

After reading the file e.g. CountLines(), I can't reset the stream with .Position, CanSeek is false. Any workaround?

Installing nuget package broke my solution, uninstalling didn't fix it.

As soon as I installed the Nuget package I received:

"The type or namespace 'MainLayout' could not be found (are you missing a using directive...
(I get that 2 times in App.razor)

I also get:
"Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the deligate return type." in App.razor.g.cs.

I've cleaned the project, shut down VS2019 Preview, deleted the obj and bin folders. Nothing helps.

Any ideas how to troubleshoot this?

Runtime error: Memory access out of bounds

I'm using the InputFile to pick images in Blazor WASM, then save them as byte arrays in IndexedDB, before uploading them to the server. It all works fine for small files, but once I have two photos in the DB at 700KB each, I get the above error message in the console, and the site errors out. I will need to store a lot of photos at camera-resolution - what is the way forward with this?

ReadRequest SharedMemoryFileListEntryStream

System.Reflection.ReflectionTypeLoadException: 'Unable to load one or more of the requested types.
Could not load type 'ReadRequest' from assembly 'Analytics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it contains an object field at offset 4 that is incorrectly aligned or overlapped by a non-object field.'

Can the name of the uploaded file be changed prior to upload

This is an awesome component! But I noticed that the File property is read-only. Is there a way to change the file name in the component? Will that be a feature after first release? Or is there a method I'm missing and didn't notice? What I'd like to do is have a file name be changed to something like a GUID, or an entry in a textbox along with a date stamp, etc.

Thank you!!!

JS error when uploading with Edge

Getting "Number expected" error on line 12 in inputfile.js when uploading with Edge.
On row: lastModified: new Date(file.lastModified).toISOString()
But: file.lastModified is undefined

Otherwise, it seems to work well, very good performance.
Hope for a 1.0 included in Blazor soon!

AspNetCore 3.0.0

Hi Steve,

Are you intending to bring this up to date or is it going to be included in the main product any time soon?

UI hanging on file upload

I've been using the BlazorInputFile and it's been working well - but something's changed and now the UI hangs on copying the file data to a memory stream. For a 1MB file this can take 5 seconds ish, when the UI is unresponsive. Have you come across anything like this before?

There is no file with ID 1. The file list may have changed

BlazorInputFile throws an exception "There is no file with ID 1. The file list may have changed".

On re-add new files, all previously created objects belonging to previous files aren't saved. Meantime, the index starts with unsaved objects that no longer exist.
Note that saving files at each selection step gives an correct index.

The Chrome inside debugger indicates a problem in inputfile.js
The debugger indicates a problem in inputfile.js

Multiple files fails with this error (Single file is ok)

Microsoft.JSInterop.JSException
HResult=0x80131500
Mensaje = Cannot read property '_blazorFilesById' of null
TypeError: Cannot read property '_blazorFilesById' of null
at getFileById (https://localhost:5001/_content/BlazorInputFile/inputfile.js:114:25)
at getArrayBufferFromFileAsync (https://localhost:5001/_content/BlazorInputFile/inputfile.js:123:20)
at Object.readFileData (https://localhost:5001/_content/BlazorInputFile/inputfile.js:76:31)
at https://localhost:5001/_framework/blazor.server.js:8:31421
at new Promise ()
at e.beginInvokeJSFromDotNet (https://localhost:5001/_framework/blazor.server.js:8:31390)
at https://localhost:5001/_framework/blazor.server.js:1:19202
at Array.forEach ()
at e.invokeClientMethod (https://localhost:5001/_framework/blazor.server.js:1:19173)
at e.processIncomingData (https://localhost:5001/_framework/blazor.server.js:1:17165)
Origen = System.Private.CoreLib
Seguimiento de la pila:
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at BlazorInputFile.RemoteFileListEntryStream.d__6.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at BlazorInputFile.FileListEntryStream.<ReadAsync>d__21.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at Analytics.Helpers.FileUtils.d__1.MoveNext() in

IFileListEntry.Data stream causes problems with using StreamReader

A StreamReader that is constructed by passing in IFileListEntry.Data as a parameter appears to be incompatible with CsvHelper. Any attempt to work with a CsvReader created using the StreamReader receives the following error when you try to use it: "Synchronous reads are not supported"

Example:

IFileListEntry file = files.FirstOrDefault();

using (var reader = new System.IO.StreamReader(file.Data))
using (var csv = new CsvReader(reader))
{
  using (var dr = new CsvDataReader(csv)) // error here: "synchronous reads are not supported"
  {
    var dt = new DataTable();
    dt.Load(dr);
  }
}

Since streams from other sources, such as reading a file into a FileStream, seem to work fine with CsvHelper, I suspect the issue may lie with something unique to the implementation of IFileListEntry.Data.

No minified inputfile.js

While optimization of my site, I noticed inputfile.js is not minified

<script src="_content/BlazorInputFile/inputfile.js"></script>

I'm using Visual Studio Extension to minified JS and CSS, since this is part of library I cannot minify this file.

OnDataRead upload status does not work for image resize

While trying to read the file upload progress, your sample code works file. However, changing the following two lines:

var ms = new MemoryStream(); await file.Data.CopyToAsync(ms);

to include file format:

var format = "image/jpeg"; var imageFile = await file.ToImageFileAsync(format, 3000, 3000); var ms = new MemoryStream(); await imageFile.Data.CopyToAsync(ms);

This causes the progress to always show 0%. Is there a way to make this work? Thanks!

How I can pass the parameter to OnChange function

I have list of models and each object have the associated image.
so I am having multiple inputfile control on page.
How I can pass the object to Onchange function so that uploaded url can be attached to model.

How to send the file to MVC controller

I'm trying to upload a file using Blazor server-side.
The file needs to be saved in an Azure blobcontainer but before that some some checks need to be performed to prevent overwritten an existing file and after saved to the blob a record in a table needs to be added.
Also a desktop application should be able to upload a file.

So I think I need a controller to do this. I've used similar with a .NET Framework v4.6 web app.

I'm having trouble understanding how to send the file to my controller. Do I need to read the file first into memory? I hope not because the files can be very large (up to 500MB).

I'm looking at the SingleFile demo:

    async Task HandleSelection(IFileListEntry[] files)
    {
        var file = files.FirstOrDefault();
        if (file != null)
        {

I assume I need to call await HttpClient.PostAsync("/api/upload/files", content) but how to go from file to content?

Or should I use a different approach?

Stopped working after load ~20MB in total

Hello everyone. There's interesting problem, that has some similarities with this issue. Actually I think it's the same.

Reproduce:

  1. Choose multifile profile(no matter, single or multifile)
  2. Pick up 3 files. 12, 8 and 8 MB.
  3. Press download button. Initially load file 12MB(it's important), then 8 and 8.
  4. Load progress in % will be: 12MB - 100%, 8 - 100%, 8 - 6%.
  5. If you would be loading 8, 8 and 12 all will be okay, then you will try some other files and the problem will show itself again.

And you know why load was stopped at 6% in the example above? Cause the method CopyToAsync stopped at position 512000 while stream was read:

{ var ms = new MemoryStream(); await file.Data.CopyToAsync(ms); }

When you are going through the imaginary limit of ~20MB all subsequent reading will be stopped at position 512000.

Remark:
Steve, let's be honest. I think, just think, that you know of this problem.
In your gif example for multifile you are choosing three files: 19MB, 12MB and 30KB, but it was downloaded in vice versa. 30KB -> 12MB -> 19MB.

It would be appreciated to see some answers.

Environment:

  1. Windows 10 build 19028
  2. Server side
  3. Asp Net Core 3.0

SharedMemoryFileListEntryStream.ReadAsync() does not return requested bytes

Relevant info: Blazor-Client WASM app, hosted with asp.net core using identity

I think this may be more of a documentation issue. When calling ReadAsync() on the stream returned by BlazorFileInput OnChange event, I typically never get the number of bytes requested. (i.e. I specify it to read 2MB, it only fills my 2MB buffer with 1MB worth of data). It correctly reports the number of bytes it actually read, but I didn't think that it would consistently under-fill the buffer when there was more data remaining than the buffer size.

I was having a bear of a time wondering why my Azure BlockBlobs were getting uploaded with 5-100% additional size. Don't be careless like me, check the bytes being read and update your buffer accordingly!

Scroll into view

I know this is not related but maybe you can point me to the right direction. Let say i have a long form, and after validation i want to show summary of all errors above the form like:

@if (ShowErrors) { <div class="alert alert-danger" role="alert" id="errors"> @foreach (var error in Errors) { <p>@error</p> } </div> }

The problem is because the form is really long one, errors div is not in a scroll view, so i want to scroll screen up to that div #errors. I can easily run via JS interop

var element = document.getElementById(elementId);
element.scrollIntoView();

my problem is i don't know when Blazor finished updating a DOM and rendering #errors div, so i call scrollIntoView too early which obviously scrolls to the wrong position. Any way i can catch an event when Blazor finishes DOM update?

Thanks!

Extremely slow upload of large files in deployed blazer server app

Hi Team,
I am working on a blazer server app that would allow user to upload load large excel files(75 to 100 MB) that would eventually be processed by the app.

When I deploy the app to Azure the file upload is extremely slow. A 75 MB file would take more than 15 minutes to upload. (The same file would upload in 15 seconds when the app is running on local host).

I have done se trials to investigate and have ruled out any network issues. More details and the code is available at:

https://stackoverflow.com/questions/65568958/extremely-slow-file-upload-to-a-blazor-server-app-deployed-as-azure-web-app/65573119#65573119

I would be really glad if you could help identify what could be done to get the file to upload faster.

Thanks

Unhandled exception rendering component: Could not find 'BlazorInputFile' in 'window'

I created a default Blazor WebAssembly application in order to learn about the BlazorInputFile. Whenever I start the application, if I go to the simple page I created with just the option to upload a file, I get the following error message described below. But if I simply refresh the page the error disappears and doesn't appear again.

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Could not find 'BlazorInputFile' in 'window'.
p/<@https://localhost:5003/_framework/blazor.webassembly.js:1:9130

I followed the steps recommended by this article:
https://www.mikesdotnetting.com/article/341/uploading-files-in-blazor

  1. In the client project: Install-Package BlazorInputFile -Version 0.2.0
  2. Add <script src="_content/BlazorInputFile/inputfile.js"></script> in index.html
  3. Add "@using System.IO" and "@using BlazorInputFile" in _Imports.razor

This error appears only when I use the Firefox Browser, if I use the Microsoft Edge this error does not appear.

The page I created is simply:

@page "/singlefile"

<h1>Single file</h1>

<p>A single file input that uploads automatically on file selection</p>

<InputFile OnChange="HandleSelection" />

<p>@status</p>

@code {
    string status;

    async Task HandleSelection(IFileListEntry[] files)
    {
        var file = files.FirstOrDefault();
        if (file != null)
        {
            // Just load into .NET memory to show it can be done
            // Alternatively it could be saved to disk, or parsed in memory, or similar
            var ms = new MemoryStream();
            await file.Data.CopyToAsync(ms);

            status = $"Finished loading {file.Size} bytes from {file.Name}";
        }
    }
}

Microsoft Edge

Can't seem to drag and drop files using the Edge browser onto the input file box.

System.Reflection.ReflectionTypeLoadException - object field at offset 4 that is incorrectly aligned or overlapped by a non-object field

System.Reflection.ReflectionTypeLoadException: 'Unable to load one or more of the requested types.
Could not load type 'ReadRequest' from assembly 'BlazorInputFile, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it contains an object field at offset 4 that is incorrectly aligned or overlapped by a non-object field.'

version 0.2.0.

this comes from.

    [StructLayout(LayoutKind.Explicit)]
    struct ReadRequest
    {
        [FieldOffset(0)] public string InputFileElementReferenceId;
        [FieldOffset(4)] public int FileId;
        [FieldOffset(8)] public long SourceOffset;
        [FieldOffset(16)] public byte[] Destination;
        [FieldOffset(20)] public int DestinationOffset;
        [FieldOffset(24)] public int MaxBytes;
    }

grafik

only works first time

Hi,
Works perfectly first time but 2nd or 3rd time it just stops and every attemp after this fails.
I am just uploading 14-18MB files.
I am choosing the file to upload each time.

Azure SignalR Message Quota

I am on the Blazor-server model. The blog post mentions message size limits, but large files (+50MB) will still need a large quantity of messages, won't they?

I ran into the quota limit on the free tier really fast after trying to upload ~70MB worth of files in total. The Azure SignalR service pricing makes it extremely cost prohibitive to be sending several thousand messages per several-megabyte upload. Should there be a big disclaimer in the blog or am I just doing something wrong and this many messages should not be in-flight with this component?

How do you change the labels?

I hope this isn't a stupid question but, how do you change the button label and remove the file name after the button.
Thanks for all you do. This is so valuable.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.