Photo Upload Problem in ASP.NET MVC My Blog Project

146 views Asked by At

When I upload a photo, the page just refresh, not upload the photo in ASP.NET MVC My Blog Project. I looked the solution in Stack OverFlow but I didn't handle this problem. I don't know to write which code here because I am firstly trying to make a blog site in ASP.NET. If you are ask to me whatever code, I publish here quickly. Thanks for cooperation.

1

There are 1 answers

1
Yat Fei Leong On

Say for example your model is

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

Here I'm storing the photo in the server (Not in the database) There goes the controller

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");
    }

There goes the View

@model ProjectName.Entities.Blog

@{
    ViewBag.Title = "BeginUploadPhoto";
}

<div class="container">


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

}

@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>
    }

}