0

I have a Blazor app where Im using BlazorInputFile from this website - https://blog.stevensanderson.com/2019/09/13/blazor-inputfile/ however the page only loads it to a Memory Stream, not copy the file to a folder on the server. I need it to copy to a folder on the server.

<div class="form-group">
    <label for="taskName">Feature Image</label>
    <InputFile OnChange="HandleFileSelected" />
</div>

@code {

IFileListEntry file;

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

async Task CountLines()
{
    numLines = 0;
    using (var reader = new System.IO.StreamReader(file.Data))
    {
        while (await reader.ReadLineAsync() != null)
        {
            numLines++;
        }
    }
}

async Task UploadFile()
{
    if (file != null)
    {
        var path = System.IO.Path.Combine(Server.MapPath("~/Uploads/"));
        string pathstring = System.IO.Path.Combine(path.ToString());
        string filename1 = Guid.NewGuid() + System.IO.Path.GetExtension(file.Name);
        bool isexists = System.IO.Directory.Exists(path);
        if (!isexists)
        {
            System.IO.Directory.CreateDirectory(pathstring);
        }
        string uploadpath = pathstring + "\\" + filename1;
        file.SaveAs(uploadpath);
    }
}

In the code above I have created a UploadFile method and taken my usual way of uploading files, but obviously it wont work because IFileListEntry does not have the SaveAs method and Server will not work on Blazor.

How am I best uploading this file to the server please? (UploadFile method will get called on form submit).

  • You have your question answered here. It is an extension of the sample code created by Steve Anderson.: mikesdotnetting.com/article/341/uploading-files-in-blazor – enet yesterday
  • @enet I am just trying to implement this now. Where we use HttpContext.Request.Form.Files.Any we get an exception 'Form = The function evaluation requires all threads to run.' when looking at the Form part. – dynmatt yesterday
0

Here is another package and sample project that uses Steve Sanderson Blazor File Input:

(Disclaimer: this is my project and Nuget Package)

https://github.com/DataJuggler/BlazorFileUpload

There is a sample project located in the Samples directory.

Nuget Package: DataJuggler.Blazor.FileUpload

And a video is here: https://youtu.be/Hj_k90mifSQ

Free Code Is Not SPAM. If it helps one person that is my goal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.