简体   繁体   English

MVC文件上传-将路径和文件名保存回数据库

[英]MVC File Upload - Saving path and filename back to database

Not sure where the issue is - the file upload is working fine and going to the correct folder however the path and filename are not being stored in the database. 不确定问题出在哪里-文件上传工作正常,并转到正确的文件夹,但是路径和文件名未存储在数据库中。

I want to use this so that I can add links to my index view for each document uploaded. 我想使用它,以便可以为每个上载的文档添加指向索引视图的链接。

Any help on this would be brilliant as I have been racking my brains for 2 days over this. 在这方面的任何帮助都会非常出色,因为我为此花了2天的时间。

Regards 问候

Andy 安迪

Model: 模型:

namespace inventIT.Models
{
using System;
using System.Collections.Generic;

public partial class ComputerInventory
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public ComputerInventory()
    {
        this.ComputerInstallations = new HashSet<ComputerInstallation>();
    }

    public int RecordID { get; set; }
    public string ComputerAdName { get; set; }
    public string ComputerBrand { get; set; }
    public string ComputerModel { get; set; }
    public string ComputerSerialNumber { get; set; }
    public string ComputerOS { get; set; }
    public System.DateTime ComputerPurchaseDate { get; set; }
    public string ComputerAddedBy { get; set; }
    public Nullable<bool> ComputerArchived { get; set; }
    public Nullable<System.DateTime> ComputerArchivedDate { get; set; }
    public string FileDesc { get; set; }
    public string FileName { get; set; }
    public string Extension { get; set; }
    public Nullable<int> FileID { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<ComputerInstallation> ComputerInstallations { get; set; }
    public virtual Lookup Lookup { get; set; }
    public virtual Lookup Lookup1 { get; set; }
    public virtual ITTeamLookup ITTeamLookup { get; set; }
    public virtual Lookup Lookup2 { get; set; }
 }
}

Controller: 控制器:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using inventIT.Models;

namespace inventIT.Controllers
{
public class ComputerInventoriesController : Controller
{
    private HAWKTRAINING_INVENTITEntities db = new HAWKTRAINING_INVENTITEntities();

    // GET: ComputerInventories
    public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page, int? PageSize)
    {


        ViewBag.searchString = "";
        ViewBag.CurrentSort = sortOrder;
        ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
        ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

        if (searchString != null)
        {
            page = 1;
        }
        else
        {
            searchString = currentFilter;
        }

        ViewBag.CurrentFilter = searchString;

        var AssessorIDs = from s in db.ComputerInventories




                          select s;
        if (!String.IsNullOrEmpty(searchString))
        {
            AssessorIDs = AssessorIDs.Where(s => s.ComputerAdName.Contains(searchString) || searchString == null || searchString == "");
        }
        switch (sortOrder)
        {
            case "name_desc":
                AssessorIDs = AssessorIDs.OrderByDescending(s => s.ComputerAdName);
                break;
            case "Date":
                AssessorIDs = AssessorIDs.OrderBy(s => s.ComputerPurchaseDate);
                break;
            case "date_desc":
                AssessorIDs = AssessorIDs.OrderByDescending(s => s.ComputerPurchaseDate);
                break;
            default:  // Name ascending 
                AssessorIDs = AssessorIDs.OrderBy(s => s.ComputerAdName);
                break;
        }
        var computerInventories = db.ComputerInventories.Include(c => c.Lookup).Include(c => c.Lookup1).Include(c => c.ITTeamLookup).Include(c => c.Lookup2);
        return View(computerInventories.Where(s => s.ComputerAdName.Contains(searchString) || searchString == null || searchString == "").OrderByDescending(c => c.ComputerAdName).ToList());
    }

    // GET: ComputerInventories/Details/5
    public ActionResult Details(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        ComputerInventory computerInventory = db.ComputerInventories.Find(id);
        if (computerInventory == null)
        {
            return HttpNotFound();
        }
        return View(computerInventory);
    }

    // GET: ComputerInventories/Create
    public ActionResult Create()
    {
        ViewBag.ComputerBrand = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerBrand"), "KeyID", "Title");
        ViewBag.ComputerOS = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerOS"), "KeyID", "Title");
        ViewBag.ComputerAddedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
        ViewBag.ComputerModel = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerModel"), "KeyID", "Title");
        return View();
    }

    // POST: ComputerInventories/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "RecordID,ComputerAdName,ComputerBrand,ComputerModel,ComputerSerialNumber,ComputerOS,ComputerPurchaseDate,ComputerAddedBy,ComputerArchived,ComputerArchivedDate,FileDesc,FileName,Extension,FileID")] ComputerInventory computerInventory)
    {

        if (ModelState.IsValid)
        {
            List<ComputerInventory> fileDetails = new List<ComputerInventory>();
            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];

                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    ComputerInventory fileDetail = new ComputerInventory()
                    {
                        FileName = fileName,
                        Extension = Path.GetExtension(fileName),
                        FileID = computerInventory.RecordID
                    };
                    fileDetails.Add(fileDetail);

                    var path = Path.Combine(Server.MapPath("~/App_Data/uploads/"), fileDetail.FileName);
                    file.SaveAs(path);
                }
            }

            computerInventory.FileID = computerInventory.FileID;
            computerInventory.Extension = computerInventory.Extension;
            computerInventory.FileDesc = computerInventory.FileDesc;
            computerInventory.FileName = computerInventory.FileName;
            db.ComputerInventories.Add(computerInventory);

            db.SaveChanges();
            return RedirectToAction("Index");
        }

        if (ModelState.IsValid)
        {
            try
            {
                db.ComputerInventories.Add(computerInventory);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                return View("Error", new HandleErrorInfo(ex, "ComputerInventories", "Create"));
            }
        }

        ViewBag.ComputerBrand = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerBrand"), "KeyID", "Title");
        ViewBag.ComputerOS = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerOS"), "KeyID", "Title");
        ViewBag.ComputerAddedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
        ViewBag.ComputerModel = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerModel"), "KeyID", "Title");
        return View(computerInventory);
    }



    [HttpPost]
    [ValidateAntiForgeryToken]
     // GET: ComputerInventories/Edit/5
    public ActionResult Edit(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        ComputerInventory computerInventory = db.ComputerInventories.Find(id);
        if (computerInventory == null)
        {
            return HttpNotFound();
        }
        ViewBag.ComputerBrand = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerBrand"), "KeyID", "Title");
        ViewBag.ComputerOS = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerOS"), "KeyID", "Title");
        ViewBag.ComputerAddedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
        ViewBag.ComputerModel = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerModel"), "KeyID", "Title");
        return View(computerInventory);
    }

    // POST: ComputerInventories/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "RecordID,ComputerAdName,ComputerBrand,ComputerModel,ComputerSerialNumber,ComputerOS,ComputerPurchaseDate,ComputerAddedBy,ComputerArchived,ComputerArchivedDate,FileDesc,FileName,Extension,FileID")] ComputerInventory computerInventory)
    {
        if (ModelState.IsValid)
        {
            db.Entry(computerInventory).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.ComputerBrand = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerBrand"), "KeyID", "Title");
        ViewBag.ComputerOS = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerOS"), "KeyID", "Title");
        ViewBag.ComputerAddedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
        ViewBag.ComputerModel = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerModel"), "KeyID", "Title");
        return View(computerInventory);
    }

    // GET: ComputerInventories/Delete/5
    public ActionResult Delete(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        ComputerInventory computerInventory = db.ComputerInventories.Find(id);
        if (computerInventory == null)
        {
            return HttpNotFound();
        }
        return View(computerInventory);
    }

    // POST: ComputerInventories/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(string id)
    {
        ComputerInventory computerInventory = db.ComputerInventories.Find(id);
        db.ComputerInventories.Remove(computerInventory);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}
}

View 视图

@model inventIT.Models.ComputerInventory

@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Computer Assets</h2>


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

{
@Html.AntiForgeryToken()

<div class="form-horizontal">
<h4>Create</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
    @Html.LabelFor(model => model.ComputerAdName, htmlAttributes: new {       @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.ComputerAdName, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.ComputerAdName, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.ComputerBrand, "ComputerBrand",   htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("ComputerBrand", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.ComputerBrand, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.ComputerModel, "ComputerModel", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("ComputerModel", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.ComputerModel, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.ComputerSerialNumber, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.ComputerSerialNumber, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.ComputerSerialNumber, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.ComputerOS, "ComputerOS", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("ComputerOS", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.ComputerOS, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.ComputerPurchaseDate, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.ComputerPurchaseDate, new { htmlAttributes = new { @class = "form-control jqueryui-marker-datepicker" } })
        @Html.ValidationMessageFor(model => model.ComputerPurchaseDate, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.ComputerAddedBy, "ComputerAddedBy", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("ComputerAddedBy", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.ComputerAddedBy, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.ComputerArchived, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <div class="checkbox">
            @Html.EditorFor(model => model.ComputerArchived)
            @Html.ValidationMessageFor(model => model.ComputerArchived, "", new { @class = "text-danger" })
        </div>
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.ComputerArchivedDate, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.ComputerArchivedDate, new { htmlAttributes = new { @class = "form-control jqueryui-marker-datepicker" } })
        @Html.ValidationMessageFor(model => model.ComputerArchivedDate, "", new { @class = "text-danger" })
    </div>
</div>


@Html.HiddenFor(x => x.FileDesc)
<input type="file" name="file" id="file" />
<input type="submit" value="submit" />

You seems to be missing Path property in your ComputerInventory and hence in your table too. 您似乎在ComputerInventory中因此在表中也缺少Path属性。 you are not setting your path to any property . 您没有设置任何属性的路径。 How do you expect it to be saved in database? 您如何期望将其保存在数据库中?

First add a column in Table as FilePath, update Model ComputerInventory and set path to this FilePath variable 首先在表中添加一列作为FilePath,更新Model ComputerInventory并将此FilePath变量的路径设置为

Class ComputerInventory()
{
    public string FilePath { get; set; }
    //other properties;
}



 computerInventory.FilePath = path;
 db.ComputerInventories.Add(computerInventory);

 db.SaveChanges();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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