RazorPage

RazorPage 上传文件示例

概览


单文件

示例:

前端代码:

<form method="post" enctype="multipart/form-data">
    <div class="form-row">
        <div class="col-md-3">
            <input class="form-control-file" type="file" name="file" />
        </div>
        <div class="col-md-auto">
            <input type="submit" value="上传" class="btn btn-primary px-5" formaction="?handler=UploadSingleFile" />
        </div>
    </div>
</form>

后端代码:

public ActionResult OnPostUploadSingleFile(IFormFile file)
{
    if(file != null && file.Length > 0)
    {
        string folderName = "Uploaded";
        string webRootPath = _hostingEnvironment.WebRootPath;
        string newPath = Path.Combine(webRootPath, folderName);
        if (!Directory.Exists(newPath))
        {
            Directory.CreateDirectory(newPath);
        }

        string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
        string fullPath = Path.Combine(newPath, fileName);
        using (var stream = new FileStream(fullPath, FileMode.Create))
        {
            file.CopyTo(stream);
        }

        StatusMessage = "操作成功。";
    }
    else
    {
        StatusMessage = "错误:失败。";
    }
    return Page();
}

多文件

示例:

前端代码:

<form method="post" enctype="multipart/form-data">
    <div class="form-row">
        <div class="col-md-3">
            <input class="form-control-file" type="file" name="files" multiple/>
    </div>
    <div class="col-md-auto">
    <input type="submit" value="上传" class="btn btn-primary px-5" formaction="?handler=UploadMultiFile" />
    </div>
    </div>
</form>

后端代码:

public ActionResult OnPostUploadMultiFile(List<IFormFile> files)
{
    if (files != null && files.Count > 0)
    {
        string folderName = "Uploaded";
        string webRootPath = _hostingEnvironment.WebRootPath;
        string newPath = Path.Combine(webRootPath, folderName);
        if (!Directory.Exists(newPath))
        {
            Directory.CreateDirectory(newPath);
        }
        foreach (IFormFile item in files)
        {
            if (item.Length > 0)
            {
                string fileName = ContentDispositionHeaderValue.Parse(item.ContentDisposition).FileName.Trim('"');
                string fullPath = Path.Combine(newPath, fileName);
                using (var stream = new FileStream(fullPath, FileMode.Create))
                {
                    item.CopyTo(stream);
                }
            }
        }
        StatusMessage = "操作成功。";
    }
    else
    {
        StatusMessage = "错误:失败。";
    }
    return Page();
}
</pre>