简体   繁体   中英

How to change uploaded image on Razor page asp.net core

I tried a file uploading method from StackOverflow and successfully uploaded the image with the IHostEnvironment setup. But I can't figure out the Editmodel . I want to delete the existing photo and add a new one in the edit form.

Here is Model:

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

    public string FeatureImage { get; set; }

Here is the 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);
    }
}

As I said, uploading the image working fine. But I can't figure out for the edit.cshtml.cs. How can I delete the existing photo and add the new image?

Here is a working sample, you could refer to:

Edit.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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM