我是这样做的:
查看.cs
<div class="row">
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="FileUpload" id="FileUpload" runat="server" />
<input type="submit" value="Save" class="btn btn-default" />
}
</div>
我正在使用HomeController
,所以你在Upload
那里创建函数。我还包括如何将文件内容存储在数据库中,而不仅仅是位置,下面的代码使用了Assignment
提供的模型,但我还将展示我如何将其保存到数据库中使用我为我的桌子创建的模型,ITEM_ATCHMT
.
如果您所拥有的只是页面上的 FileUpload 控件并且没有使用它在视图上填充数据,则您不必传入模型并将其传回,因此此函数不会这样做,而我的 View 不会'不要使用模型 - 你的模型可能不同,如果在你的视图上使用,你可能希望保持你的模型被传入、返回。
我为多个对象设置了一次发布,所以我有一个List<ViewDataUploadFilesResult>
接收它们的数据,并在将每个文件及其元数据保存到数据库的过程中进行迭代。不过,您可以使用它一次只保存一个文件,因此我添加了代码并注释掉了多个文件的部分。希望它不会让任何人感到困惑 - 最后只是两种不同的方式来做同样的事情。
家庭控制器.cs
[HttpPost]
public ActionResult Upload()
{
//var r = new List<ViewDataUploadFilesResult>();
var r = new ViewDataUploadFilesResult();
Assignment a = new Assignment();
if (ModelState.IsValid)
{
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
if (file.ContentLength > 0)
{
int fileSize = file.ContentLength;
var fileName = Path.GetFileName(file.FileName);
//You could do this to get the content -
//it would need a varbinary(max) field
//Stream posted file into a byte array
byte[] fileByteArray = new byte[fileSize];
file.InputStream.Read(fileByteArray, 0, fileSize);
//Uploading properly formatted file to server.
string fileLocation = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
if (!Directory.Exists(Server.MapPath("~/App_Data/uploads")))
Directory.CreateDirectory(Server.MapPath("~/App_Data/uploads"));
file.SaveAs(fileLocation);
// I used a ViewModel to collect my file information
ViewDataUploadFilesResult r = new ViewDataUploadFilesResult();
r.Name = fileName;
r.FilePath = fileLocation;
r.Length = fileSize;
r.FileObj = file;
r.Content = fileByteArray;
// I provided a list so I could upload multiple files
// at once, but you might've just had the one item, above
//r.Add(new ViewDataUploadFilesResult()
//{
// Name = fileName,
// FilePath = fileLocation,
// Length = fileSize,
// FileObj = file,
// Content = fileByteArray
//});
// Below is for singular ViewDataUploadFilesResult objects (uncomment the loop for multiple)
//for (int i = 0; i < r.Count; i++)
//{
//assignment.FileLocation = r[i].FilePath; //multiple objects need an index, [i]
assignment.FileLocation = r.FilePath; //singular objects don't
assignment.Status = "Uploaded";
assignment.Comments = "Completed";
//}
// You also could've just not used ViewDataUploadFilesResult
// at all, and just used assignment, only
// and just added fileSize, fileContents, etc. to it
EFModel db = new EFModel(); // this is your Entity Framework context
db.Assignments.Add(assignment); //"Assignments" would be your table
db.SaveChanges();
}
return RedirectToAction("Index");
//return View("Index", r);
}
}
return View();
}
附加型号
ViewDataUploadFilesResult.cs
public class ViewDataUploadFilesResult
{
public string Name { get; set; }
public string FilePath { get; set; }
public int Length { get; set; }
public HttpPostedFileBase FileObj { get; set; }
public byte[] Content { get; set; }
}
对我来说,不是使用整个 ViewModel,而是我的 Attachments 表的实际模型:
public partial class ITEM_ATCHMT
{
[Key]
public Guid ATCHMT_ID { get; set; }
public int ITEM_ID { get; set; }
[ForeignKey("ITEM_ID")]
public virtual ITEM item { get; set; }
[Required]
[StringLength(50)]
public string USER_NAME_DESC { get; set; }
[Required]
[StringLength(250)]
public string FILE_NAME_TXT { get; set; }
[Required]
public byte[] FILE_CNTNT_CD { get; set; }
[Required]
[StringLength(10)]
public string FILE_TYPE_DESC { get; set; }
public DateTime CREATED_DT { get; set; }
}
并说我想将它与这个项目相关联:
public partial class ITEM
{
[Key]
public int ITEM_ID { get; set; }
[Required]
[StringLength(50)]
public string NAME { get; set; }
}
要使用实体框架保存任何数据,您只需要填充该模型,然后.SaveChanges()
在您的上下文中执行:
EFModel db = new EFModel(); // this is my Entity Framework context
ITEM item = new ITEM();
item.NAME = "My Item";
db.ITEM.Add(item); //"ITEM" is my table and name of an EF model, "item" is the object that represents my model
db.SaveChanges();
如果ITEM_ID
设置为自动递增:
ITEM_ATCHMT atchmt_model = new ITEM_ATCHMT();
atchmt_model.ATCHMT_ID = Guid.NewGuid();
atchmt_model.ITEM_ID = item.ITEM_ID // <-- this should have the ID
atchmt_model.USER_NAME_DESC = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
atchmt_model.FILE_CNTNT_CD = r.Content;
atchmt_model.FILE_NAME_TXT = r.Name;
atchmt_model.FILE_TYPE_DESC = r.Name.Split('.')[1];
atchmt_model.CREATED_DT = DateTime.Now;
db.ITEM_ATCHMT.Add(atchmt_model); //"ITEM_ATCHMT" is my table
db.SaveChanges();
