我设法让我的项目上传一个字节存储的文件以及其他详细信息,现在我需要编辑该记录并覆盖该文件。到目前为止,我所做的只是向包含新文件的数据库添加了新行-我的问题是我该如何覆盖该文件。希望我已经发布了足够的代码,任何帮助都将非常棒,谢谢
控制器
using QIHubProjectTemplate.Helpers;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.DirectoryServices.AccountManagement;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QIHubProjectTemplate.Models;
using QIHubProjectTemplate.Repositories;
using QIHubProjectTemplate.ViewModel;
using static System.Net.WebRequestMethods;
using System.Web.Routing;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Net;
namespace UploadAndDisplayImageInMvc.Controllers
{
[RoutePrefix("Content")]
[ValidateInput(false)]
public class ContentController : Controller
{
private DBContext db = new DBContext();
[Route("Index")]
[HttpGet]
public ActionResult Index()
{
Content Content = new Content();
PrincipalContext context = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(context, User.Identity.Name);
DefaultVars defaultVars = new DefaultVars();
string UserName = User.Identity.Name.Replace(@"CYMRU\", string.Empty);
Session["NadexName"] = UserName;
Content = defaultVars.retVars(user, UserName);
var content = db.Contents.Select(s => new
{
s.ID,
s.Title,
s.Image,
s.Contents,
s.Description,
s.FullName,
s.Skills,
s.EmailID,
s.ContactNo,
s.Position,
s.CreatedOn,
s.nadex,
s.HospitalSite,
s.Preferred,
s.QITraining,
s.Membership,
s.AreaOfInterest,
s.PhoneNumber,
s.ProjectCategory,
s.Aims,
s.Stage,
s.CompletitionDate,
s.KeyWord1,
s.KeyWord2
});
List<ContentViewModel> contentModel = content.Select(item => new ContentViewModel()
{
ID = item.ID,
Title = item.Title,
Image = item.Image,
Description = item.Description,
Contents = item.Contents,
FullName = item.FullName,
Skills = item.Skills,
EmailID = item.EmailID,
ContactNo = item.ContactNo,
Position = item.Position,
CreatedOn = item.CreatedOn,
nadex = item.nadex,
HospitalSite = item.HospitalSite,
Preferred = item.Preferred,
QITraining = item.QITraining,
Membership = item.Membership,
AreaOfInterest = item.AreaOfInterest,
PhoneNumber = item.PhoneNumber,
ProjectCategory = item.ProjectCategory,
Aims = item.Aims,
Stage = item.Stage,
CompletitionDate = item.CompletitionDate,
KeyWord1 = item.KeyWord1,
KeyWord2 = item.KeyWord2
}).ToList();
return View(contentModel);
}
/// <summary>
/// Retrive Image from database
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ActionResult RetrieveImage(int id)
{
byte[] cover = GetImageFromDataBase(id);
if (cover != null)
{
return File(cover, "application.pdf");
}
else
{
return null;
}
}
/// <summary>
///
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public byte[] GetImageFromDataBase(int Id)
{
var q = from temp in db.Contents where temp.ID == Id select temp.Image;
byte[] cover = q.First();
return cover;
}
[HttpPost]
public FileResult DownloadFile(int? fileId)
{
byte[] bytes;
string fileName, Description;
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["dbContext"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Title, Description, Image FROM [Contents] WHERE Id=@Id";
cmd.Parameters.AddWithValue("@ID", fileId);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["Image"];
Description = sdr["Description"].ToString();
fileName = sdr["Title"].ToString();
}
con.Close();
}
}
return File(bytes, Description, fileName);
}
[Route("Create")]
[HttpPost]
public ActionResult Create(ContentViewModel model)
{
HttpPostedFileBase file = Request.Files["ImageData"];
ContentRepository service = new ContentRepository();
int i = service.UploadImageInDataBase(file, model);
if (i == 1)
{
return RedirectToAction("Index");
}
return View(model);
}
[HttpGet]
public ActionResult Create()
{
Content Content = new Content();
PrincipalContext context = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(context, User.Identity.Name);
DefaultVars defaultVars = new DefaultVars();
string UserName = User.Identity.Name.Replace(@"CYMRU\", string.Empty);
Session["NadexName"] = UserName;
Content = defaultVars.retVars(user, UserName);
return View();
}
public async Task<ActionResult> RenderImage(int id)
{
Content item = await db.Contents.FindAsync(id);
byte[] photoBack = item.Image;
return File(photoBack, "image/png");
}
public ActionResult GetPDF(int id)
{
var pdfData = (byte[])db.Contents.Find(id).Image;
return File(pdfData, "application/pdf");
}
public async Task<ActionResult> Index(string searchString)
{
var content = from c in db.Contents
select c;
if (!String.IsNullOrEmpty(searchString))
{
content = content.Where(s => s.KeyWord1.Contains(searchString));
}
return View(await content.ToListAsync());
}
public ActionResult Edit(Int32 ID)
{
var ContentData = db.Contents.Where(x => x.ID == ID).FirstOrDefault();
if (ContentData != null)
{
TempData["ID"] = ID;
TempData.Keep();
return View(ContentData);
}
return View();
}
[HttpPost]
public ActionResult Edit(Content content)
{
HttpPostedFileBase file = Request.Files["ImageData"];
EditRepository service = new EditRepository();
int i = service.UploadImageInDataBaseEdit(file, content);
Int32 ID = (int)TempData["ID"];
var ContentData = db.Contents.Where(x => x.ID == ID).FirstOrDefault();
if (ContentData != null)
{
ContentData.FullName = content.FullName;
ContentData.Position = content.Position;
ContentData.Skills = content.Skills;
ContentData.EmailID = content.EmailID;
ContentData.ContactNo = content.ContactNo;
ContentData.PhoneNumber = content.PhoneNumber;
ContentData.HospitalSite = content.HospitalSite;
//ContentData.Department = content.Department;
//ContentData.AreaOfInterest = content.AreaOfInterest;
//ContentData.Membership = content.Membership;
//ContentData.QITraining = content.QITraining;
//ContentData.AreaOfInterest = content.AreaOfInterest;
//ContentData.ProjectCategory = content.ProjectCategory;
//ContentData.Title = content.Title;
//ContentData.Description = content.Description;
//ContentData.Aims = content.Aims;
//ContentData.Stage = content.Stage;
//ContentData.CompletitionDate = content.CompletitionDate;
//ContentData.KeyWord1 = content.KeyWord1;
//ContentData.KeyWord2 = content.KeyWord2;
db.Entry(ContentData).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
}
}
编辑视图
@model QIHubProjectTemplate.Models.Content
@{
ViewBag.Title = "Edit";
}
<script type="text/javascript">
function fileCheck(obj) {
var fileExtension = ['pdf'];
if ($.inArray($(obj).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Only '.pdf' formats are allowed.");
}
}
</script>
<h2>Edit</h2>
@using (Html.BeginForm("Edit", "Content", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="card bg-light mb-3">
<div class="card-header">
<h2 class="text-center">Quality & Innovation HUB Members and Clinician Project Submission e-Form</h2>
<p class="one"></p>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-3">
<label for="x_QIHubProjectTemplate_FullName" class="control-label jmLabelUnbold medium"><span class="badge badge-pill badge-primary">1</span> Full Name</label>
@*@Html.TextBoxFor(x => x.FullName, new { @Value = "Michelle Mabbs", style = "width: 200px;" })*@
@Html.EditorFor(x => x.FullName, null, new { @Value = "Michelle Mabbs", @class = "form-control" })
</div>
<div class="col-md-3">
<label for="x_QIHubProjectTemplate_Position" class="control-label jmLabelUnbold medium"><span class="badge badge-pill badge-primary">2</span> Job Title</label>
@Html.EditorFor(x => x.Position, null, new { @Value = "Developer", @class = "form-control" })
</div>
<div class="col-md-3">
<label for="x_QIHubProjectTemplate_Skill" class="control-label jmLabelUnbold medium"><span class="badge badge-pill badge-primary">3</span> Primary Skill Set</label>
@Html.EditorFor(x => x.Skills, null, new { @Value = "SQL", @class = "form-control" })
</div>
<div class="col-md-3">
<label for="x_QIHubProjectTemplate_EmailID" class="control-label jmLabelUnbold medium"><span class="badge badge-pill badge-primary">4</span> Email Address</label>
@Html.EditorFor(x => x.EmailID, null, new { @Value = "michelle.mabbs@wales.nhs.uk", @class = "form-control" })
</div>
</div>
<br>
<div class="row">
<div class="col-md-3">
<label for="x_QIHubProjectTemplate_Contact" class="control-label jmLabelUnbold medium"><span class="badge badge-pill badge-primary">5</span> Mobile Telephone</label>
@Html.EditorFor(x => x.ContactNo, null, new { @Value = 07565611852, @class = "form-control" })
</div>
<div class="col-md-3">
<label for="x_QIHubProjectTemplate_Position" class="control-label jmLabelUnbold medium"><span class="badge badge-pill badge-primary">6</span> Other Telephone</label>
@Html.EditorFor(x => x.PhoneNumber, null, new { @Value = 07565611852, @class = "form-control" })
</div>
<div class="col-md-3">
<label for="x_QIHubProjectTemplate_HospitalSite" class="control-label jmLabelUnbold medium"><span class="badge badge-pill badge-primary">7</span> Hospital Site</label>
@Html.EditorFor(x => x.HospitalSite, null, new { @Value = "Abergele", @class = "form-control" })
</div>
</div>
<input type="file" name="ImageData" id="ImageData" onchange="fileCheck(this);" />
@Html.ValidationMessageFor(x => x.Image)
</div>
</div>
<p>
<input type="submit" value="Save" />
</p>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
EditRepository
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using QIHubProjectTemplate.Models;
using QIHubProjectTemplate.ViewModel;
namespace QIHubProjectTemplate.Repositories
{
public class EditRepository
{
private readonly DBContext db = new DBContext();
public int UploadImageInDataBaseEdit(HttpPostedFileBase file, Content content)
{
content.Image = ConvertToBytes(file);
var Content = new Content
{
Title = content.Title,
Description = content.Description,
Contents = content.Contents,
Image = content.Image,
FullName = content.FullName,
Skills = content.Skills,
EmailID = content.EmailID,
ContactNo = content.ContactNo,
Position = content.Position,
CreatedOn = content.CreatedOn,
UserName = content.UserName,
nadex = content.nadex,
HospitalSite = content.HospitalSite,
Department = content.Department,
Preferred = content.Preferred,
QITraining = content.QITraining,
Membership = content.Membership,
AreaOfInterest = content.AreaOfInterest,
PhoneNumber = content.PhoneNumber,
ProjectCategory = content.ProjectCategory,
Aims = content.Aims,
Stage = content.Stage,
CompletitionDate = content.CompletitionDate,
KeyWord1 = content.KeyWord1,
KeyWord2 = content.KeyWord2
};
db.Contents.Add(Content);
int i = db.SaveChanges();
if (i == 1)
{
return 1;
}
else
{
return 0;
}
}
public byte[] ConvertToBytes(HttpPostedFileBase image)
{
byte[] imageBytes = null;
BinaryReader reader = new BinaryReader(image.InputStream);
imageBytes = reader.ReadBytes((int)image.ContentLength);
return imageBytes;
}
}
}