首页 > 解决方案 > 无法获取 Blazor 文件上传以上传文件

问题描述

我有一个 Blazor 应用程序,我在其中使用此网站上的 BlazorInputFile - https://blog.stevensanderson.com/2019/09/13/blazor-inputfile/但是该页面仅将其加载到内存流中,而不是将文件复制到服务器上的文件夹。我需要将其复制到服务器上的文件夹中。

<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);
    }
}

在上面的代码中,我创建了一个 UploadFile 方法并采用了我通常的上传文件的方式,但显然它不会工作,因为 IFileListEntry 没有 SaveAs 方法并且 Server 无法在 Blazor 上工作。

请问我如何最好地将这个文件上传到服务器?(UploadFile 方法将在表单提交时被调用)。

标签: file-uploadblazor

解决方案


推荐阅读