【问题标题】:How to change uploaded image on Razor page asp.net core如何在 Razor 页面 asp.net core 上更改上传的图像
【发布时间】:2020-09-14 14:27:52
【问题描述】:

我尝试了一种来自 StackOverflow 的文件上传方法,并使用 IHostEnvironment 设置成功上传了图像。但我无法弄清楚Editmodel。我想删除现有照片并在编辑表单中添加一张新照片。

这是模型:

[Key]
    public int PostID { get; set; }
[Required]
    [StringLength(160)]
    public string Title { get; set; }

    public string FeatureImage { get; set; }

这里是 Create.cshtml.cs:

public class CreateModel : PageModel
{
    private readonly RazorApp.Data.ApplicationDbContext _context;
    private readonly IHostEnvironment hostingEnvironment;
    public CreateModel(RazorApp.Data.ApplicationDbContext context, IHostEnvironment environment)
    {
        this.hostingEnvironment = environment;
        _context = context;
    }
    [BindProperty]
    public Post Post { get; set; }

    [BindProperty]
    public IFormFile Image { get; set; }

    
    public async Task<IActionResult> OnPostAsync()
    {
        if (this.Image != null)
        {
            var fileName = GetUniqueName(this.Image.FileName);
            var uploads = Path.Combine(hostingEnvironment.ContentRootPath, "wwwroot/uploads");
            var filePath = Path.Combine(uploads, fileName);
            this.Image.CopyTo(new FileStream(filePath, FileMode.Create));
            this.Post.FeatureImage = fileName; // Set the file name
        }
        var emptyPost = new Post();
        if (await TryUpdateModelAsync<Post>(
            emptyPost,
            "post",
            p => p.Title, p => p.FeatureImage))
        {
            _context.Post.Add(Post);
            await _context.SaveChangesAsync();
            return RedirectToPage("./Index");
        }

        return Page();
    }
    private string GetUniqueName(string fileName)
    {
        fileName = Path.GetFileName(fileName);
        return Path.GetFileNameWithoutExtension(fileName)
               + "_" + Guid.NewGuid().ToString().Substring(0, 4)
               + Path.GetExtension(fileName);
    }
}

正如我所说,上传图片工作正常。但我无法弄清楚edit.cshtml.cs。如何删除现有照片并添加新图像?

【问题讨论】:

    标签: c# asp.net-core razor-pages


    【解决方案1】:

    这是一个工作示例,您可以参考:

    编辑.cshtml

    <div class="col-md-4">
        <form method="post" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="Post.PostID" />
            <div class="form-group">
                <label asp-for="Post.Title" class="control-label"></label>
                <input asp-for="Post.Title" class="form-control" />
                <span asp-validation-for="Post.Title" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Post.FeatureImage" class="control-label"></label>
                <input asp-for="Post.FeatureImage" class="form-control" />
                <span asp-validation-for="Post.FeatureImage" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label  class="control-label">New Image</label>
                <input asp-for="Image" class="form-control" />
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
    

    编辑.cshtml.cs

     public class EditModel : PageModel
    {
        private readonly ChangeUploadedImage.Data.MyDbContext _context;
        private readonly IHostingEnvironment hostingEnvironment;
    
        public EditModel(MyDbContext context, IHostingEnvironment environment)
        {
            _context = context;
            hostingEnvironment = environment;
        }
    
        [BindProperty]
        public Post Post { get; set; }
    
        [BindProperty]
        public IFormFile Image { get; set; }
    
        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }
    
            if (this.Image != null)
            {
                var path = Path.Combine(hostingEnvironment.ContentRootPath, "wwwroot/uploads", Post.FeatureImage);
    
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }
                var fileName = GetUniqueName(this.Image.FileName);
                var uploads = Path.Combine(hostingEnvironment.ContentRootPath, "wwwroot/uploads");
                var filePath = Path.Combine(uploads, fileName);
                this.Image.CopyTo(new FileStream(filePath, FileMode.Create));
                this.Post.FeatureImage = fileName;
            }
            _context.Attach(Post).State = EntityState.Modified;
    
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PostExists(Post.PostID))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToPage("./Index");
        }
    
        private string GetUniqueName(string fileName)
        {
            fileName = Path.GetFileName(fileName);
            return Path.GetFileNameWithoutExtension(fileName)
                   + "_" + Guid.NewGuid().ToString().Substring(0, 4)
                   + Path.GetExtension(fileName);
        }
    }
    

    【讨论】:

    • 谢谢!我忘了在 cshtml 文件中添加 multipart/form-data。我还使用了 var postToUpdate = await _context.Post.FindAsync(id);这就是为什么我无法编辑。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2018-10-21
    • 2021-11-18
    • 2020-08-14
    • 2018-06-05
    • 2020-11-21
    • 2020-07-19
    • 2018-03-11
    相关资源
    最近更新 更多