You must Sign In to post a response.
  • Category: ASP.Net MVC

    Image upload and save that to the folder in MVC controller

    am new to MVC technology am unable to store images in the root folder of the solution

    var fileSavePath = (HttpContext.Server.MapPath("\\Logo\\" + fileName + "_" + DateTime.Now.ToShortDateString()));

    httpPostedFile.SaveAs(fileSavePath);

    Thanks & Advance
    Prem kumar A
  • #768275
    Hi,

    You can easily add the uploaded images into the folders in server side.
    For uploading Image or Document we need to user HTTPPOST method to post the image/document into the server.

    Suppose consider below is your controller file.

    public class ImageController : Controller
    {
    public ActionResult Create()
    {
    return View(new ImageViewUploadModel());
    }
    }



    and you have created View for this controller, like one Browse button and text box along with the submit button.
    Now you text box will contains the path of the uploaded item, so we get those item using the below code.


    @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue.ToString(), new { type = "file" })


    And now again the controller should be called with the POST tag,


    [HttpPost]
    [ValidateAntiForgeryToken] // Not mandatory
    public ActionResult Create(ImageViewUploadModel model)
    {
    var validImageTypes = new string[]
    {
    "image/gif",
    "image/jpeg",
    "image/png"
    }

    if (model.ImageUpload == null || model.ImageUpload.ContentLength == 0)
    {
    ModelState.AddModelError("ImageUpload", "This field is required");
    }
    else if (!imageTypes.Contains(model.ImageUpload.ContentType))
    {
    //Error Msg
    }

    if (ModelState.IsValid)
    {
    var image = new Image
    {
    Title = model.Title,
    AltText = model.AltText,
    Caption = model.Caption
    }

    if (model.ImageUpload != null && model.ImageUpload.ContentLength > 0)
    {
    var uploadDir = "~/uploads"
    var imagePath = Path.Combine(Server.MapPath(uploadDir), model.ImageUpload.FileName);
    var imageUrl = Path.Combine(uploadDir, model.ImageUpload.FileName);
    model.ImageUpload.SaveAs(imagePath);
    image.ImageUrl = imageUrl;
    }

    db.Create(image);
    db.SaveChanges(); / / Save the changes in the Server.
    return RedirectToAction("Index"); // Return to the index page
    }

    return View(model);
    }



    Thanks,
    Mani

  • #768282
    You can use given code snippet to upload Image in folder and image path in Sql server database and retrieve from Database using C#
     try
    {
    if (flupBookPic.HasFile)
    {
    fileName = flupBookPic.FileName;
    filePath = Server.MapPath("BookPictures/" + System.Guid.NewGuid() + fileName);
    flupBookPic.SaveAs(filePath);
    cmd.Parameters.AddWithValue("@BookPicName", fileName);
    int getPos = filePath.LastIndexOf("\\");
    int len = filePath.Length;
    getPath = filePath.Substring(getPos, len - getPos);
    pathToStore = getPath.Remove(0, 1);
    cmd.Parameters.AddWithValue("@BookPicPath", pathToStore);
    }

    Another example for upload Image in folder and image path in Project Folder in MVC

    Public ActionResult Index(FormCollection fc, HttpPostedFileBase file)
    {
    tbl_details tbl = new tbl_details();
    var allowedExtensions = new[] { ".Jpg", ".png", ".jpg", "jpeg" };
    tbl.Id = fc["Id"].ToString();
    tbl.Image_url = file.ToString(); //getting complete url
    tbl.Name = fc["Name"].ToString();
    var fileName = Path.GetFileName(file.FileName);
    var ext = Path.GetExtension(file.FileName);
    if (allowedExtensions.Contains(ext))
    {
    string name = Path.GetFileNameWithoutExtension(fileName); //getting file name without extension
    string myfile = name + "_" + tbl.Id + ext; //appending the name with id
    var path = Path.Combine(Server.MapPath("~/Img"), myfile);
    tbl.Image_url = path;
    obj.tbl_details.Add(tbl);
    obj.SaveChanges();
    file.SaveAs(path);
    } else {
    ViewBag.message = "Please choose your Image file";
    }
    return View();
    }


Sign In to post your comments