0

当我上传照片时,页面只是刷新,而不是在 ASP.NET MVC My Blog Project 中上传照片。我在 Stack OverFlow 中查看了解决方案,但我没有处理这个问题。我不知道在这里写什么代码,因为我首先尝试在 ASP.NET 中创建一个博客站点。如果你问我什么代码,我会很快在这里发布。谢谢合作。

4

1 回答 1

0

例如说你的模型是

public class blog
{
public int Id { get; set; }
public string Code { get; set; }
public string Photo1 { get; set; }
}

在这里,我将照片存储在服务器中(不在数据库中)控制器去了

public ActionResult BeginUploadPhoto(int Id)
    {

        var Blog= db.blog.Where(a => a.Id == Id).FirstOrDefault();

        return View(Blog);
    }

public ActionResult UploadPhoto(int? Id, HttpPostedFileBase Logo)
    {

        BlogCP = db.Blog.Find(Id);

        WebImage img = new WebImage(Logo.InputStream);
        if (img.Width > 500)
            img.Resize(500, 500);
        // to reduce the size upon upload

        string extension = Path.GetExtension(Logo.FileName);
        // get your photo extenstion
        string filename = Guid.NewGuid().ToString();
        // rename the upload photo
        var path = Path.Combine(Server.MapPath("~/BlogPhoto/"), filename + extension);
        // make sure that you create a folder BlogPhoto in your project or you can 
        //name it anything you like
        string savepath = "~/BlogPhoto/" + filename + extension;
        BlogCP.Photo1= savepath;
        
        img.Save(path);
        // save photo in your server

        if (ModelState.IsValid)
        {
            

            db.Entry(BlogCP ).Property(r => r.Photo1).IsModified = true;
            db.SaveChanges();
            return RedirectToAction("Index","Staff");
        }


        return RedirectToAction("Index");
    }

那里是视图

@model ProjectName.Entities.Blog

@{
    ViewBag.Title = "BeginUploadPhoto";
}

<div class="container">


@if (Model.Photo1 != null)
{
    <img id="Preview" class="img-thumbnail" src=@Model.Photo1/>

}

@using (Html.BeginForm("UploadPhoto", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

    {
        @Html.HiddenFor(m => m.Id)
        <div>
            <a>Select and upload Photo</a>
            <input type="file" id="Logo" name="Logo" 
<input type="file" id="Logo" name="Logo" accept="image/*" onchange="loadFile(event)">
        </div>

        <div class="form-group">
            <button id="btnUpload"
                    class="btn btn-sm btn-primary"
                    formnovalidate="formnovalidate"
                    data-pdsa-action="upload">
                <i class="glyphicon glyphicon-upload"></i>
                &nbsp;Upload
            </button>
        </div>
    }

}
于 2020-08-03T11:22:30.623 回答