如何使用剃刀编辑数据库中的文件?

How to edit files in a database with razor?

我想创建对 sql 数据库中的文件执行 CRUD 操作的剃刀页面。我设法使用 IFormFile 和 MemoryStream 将文件上传到数据库,但我无法以相同的方式 update/replace 它们。当我 select 新文件并单击“保存”时,我收到一条消息,提示没有文件 selected。

我尝试了以下代码

File.cs

namespace MyApp.Models
{
    public class File
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public byte[]? Content { get; set; }
    }
}
Edit.cshtml

@page
@model MyApp.Pages.Files.EditModel

@{
    ViewData["Title"] = "Edit";
    Layout = "~/Pages/Shared/_Layout.cshtml";
}

<h1>Edit</h1>

<h4>File</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="File.Id" />
            <div class="form-group">
                <label asp-for="File.Title" class="control-label"></label>
                <input asp-for="File.Title" class="form-control" />
                <span asp-validation-for="File.Title" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="File.Description" class="control-label"></label>
                <input asp-for="File.Description" class="form-control" />
                <span asp-validation-for="File.Description" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="FileUpload.FormFile"></label>
                <input asp-for="FileUpload.FormFile" type="file">
                <span asp-validation-for="FileUpload.FormFile"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-page="./Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Edit.cshtml.cs

#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using MyApp.Data;
using MyApp.Models;

namespace MyApp.Pages.Files
{
    public class EditModel : PageModel
    {
        private readonly ApplicationDbContext _context;

        public EditModel(ApplicationDbContext context)
        {
            _context = context;
        }

        [BindProperty]
        public File File { get; set; }

        [BindProperty]
        public BufferedSingleFileUploadDb FileUpload { get; set; }

        public class BufferedSingleFileUploadDb
        {
            [Required]
            [Display(Name = "File")]
            public IFormFile FormFile { get; set; }
        }

        public async Task<IActionResult> OnGetAsync(string id)
        {
            if (id == null)
            {
                return NotFound();
            }

            File = await _context.File.FirstOrDefaultAsync(m => m.Id == id);

            if (File == null)
            {
                return NotFound();
            }
            return Page();
        }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            using (var memoryStream = new MemoryStream())
            {
                await FileUpload.FormFile.CopyToAsync(memoryStream);

                // Upload the file if less than 2 MB
                if (memoryStream.Length < 2097152)
                {
                    File.Content = memoryStream.ToArray();
                }
                else
                {
                    ModelState.AddModelError("File", "The file is too large.");
                }
            }

            _context.Attach(File).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!FileExists(File.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return RedirectToPage("./Index");
        }

        private bool FileExists(string id)
        {
            return _context.File.Any(e => e.Id == id);
        }
    }
}

将 enctype="multipart/form-data" 添加到您的表单元素。 – 迈克·布林德