0

I know tis is not a new question, but I've looked at all the topics related and coudn't find my answer. My proble is that I have stored image data into sql db, but can't display them on edits or index (MVC 5). Can you please help me, thanks in advance. Here are my codes:

CONTROLLER

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "DrvId,FullName,Address,Postcode,Contact,Email,County,File,Date")] DriverReg driverReg, HttpPostedFileBase[] files)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    /*Lopp for multiple files*/
                    foreach (HttpPostedFileBase file in files)
                    {
                        /*Geting the file name*/
                        string filename = System.IO.Path.GetFileName(file.FileName);
                        /*Saving the file in server folder*/
                        file.SaveAs(Server.MapPath("~/Content/UploadedFiles/" + filename));
                        string filepathtosave = "UploadedFiles/" + filename;
                        /*HERE WILL BE YOUR CODE TO SAVE THE FILE DETAIL IN DATA BASE*/
                    }

                    ViewBag.Message = "File Uploaded successfully.";
                }
                catch
                {
                    ViewBag.Message = "Error while uploading the files.";
                }

                db.DriversReg.Add(driverReg);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(driverReg);
        }

MODEL

namespace HopeRemovalsFinal.Models
{
    public class DriverReg
    {
        [Key]
        public int DrvId { get; set; }
        public string FullName { get; set; }
        public string Address { get; set; }
        public string Postcode { get; set; }
        public string Contact { get; set; }
        public string Email { get; set; }
        public string County { get; set; }
        [DataType(DataType.Upload)]
        [Display(Name ="Upload File")]
        [Required(ErrorMessage ="Please choose file to upload")]
        public string File { get; set; }
    //    public string FileName { get; set; }
        public DateTime Date { get; set; }

    }
    public class DriverDbContext : DbContext
    {
        public DriverDbContext()
            : base("VanRemovals")
        {
        }

        public static DriverDbContext Create()
        {
            return new DriverDbContext();
        }

          public DbSet<DriverReg> DriversReg { get; set; }

    }
}

DETAILS VIEW

            <dt>
                @Html.DisplayNameFor(model => model.File)
            </dt>

            <dd>
                @Html.DisplayFor(model => model.File)
            </dd>

DATABASE RESULTS

 Create New
FullName    Address     Postcode    Contact     Email   County  Upload File     Date    
John    manchester  M32 7DD     098764587   [email protected]   Lancashire  uk_map.png  19/04/2016 00:00:00     Edit | Details | Delete

The UploadedFiles folder is empty but the file has been saved on db. Thanks for your help.

5
  • When you say "file data on db" and "file has been saved", are you talking about the file itself being saved to the db? Or are you saving the location on the file system as a string to that field "File" Commented Apr 19, 2016 at 13:16
  • HI guys,yes the file has been saved on the database, but can't display on details view Commented Apr 19, 2016 at 13:30
  • Sure? Or have you saved name only?? Commented Apr 19, 2016 at 13:32
  • Also, from the code you show, we never see you assign the File field on your passed in DriverReg object. Commented Apr 19, 2016 at 13:39
  • foreach (HttpPostedFileBase file in files): files is probably null Commented Apr 19, 2016 at 14:32

2 Answers 2

1

I found several errors in your code. So... this is my solution:

Model:

[DataType(DataType.Upload)]
[Display(Name = "Upload File")]
[Required(ErrorMessage = "Please choose file to upload")]
[NotMapped]
public HttpPostedFileBase File { get; set; }

public string FileName { get; set; }

View:

@Html.TextBoxFor(model => model.File, new { type = "file" })

Controller:

public ActionResult Create(DriverReg driverReg)
{
    ...
    var file = driverReg.File;
    var fileName = "~/Content/UploadedFiles/" + file.FileName;
    file.SaveAs(Server.MapPath(fileName));
    driverReg.FileName = fileName;
    ...
}

Detail View:

<dt>
    @Html.DisplayNameFor(model => model.File)
</dt>
<dd>
    <img src="@Model.FileName" />
</dd>
Sign up to request clarification or add additional context in comments.

1 Comment

driverReg.FileName is set to an absolute path using MapPath, making it unusable for the img tag. Better to store a relative path.
0

It seems odd that Create allows multiple files, while class DriverReg only has a string File (or FileName - not clear at the moment) that isn't a collection.

I'd say change Create method to accept a single file object.
If necessary also adjust the form to Post/Upload only one file.

Then, inside Create change this:

string filepathtosave = "UploadedFiles/" + filename;

to this:

driverReg.File = "UploadedFiles/" + filename;

You may need to change more that we're not seeing here, but I think doing all the above should make it better already.

6 Comments

Thanks Peter, but I changed for the above, and still only saves on database, not on UploadedFiles folder and can't display images either.
@prezequias He is right though. Your model only allows one "File" which we can only assume you intend to store the file path in this field and not the binary file data. You are passing in a posted file array and looping through them. Are you just expecting one file?
Does saving the file cause an Exception? If so, check the access rights for that folder. Or if no Exception occurs then maybe it is saved, but not where you are looking for it.
Yes, I know what you mean, I want want to pass one file, thanks
No, there is no Exception, it goes strait through, I've checked and it not saved anywhere.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.