我想在ASP.NET MVC 5中实现“上传文件”功能。但我面临两个问题。
问题1 如何强力键入文件上传到模型属性?
问题2 如何仅允许某些文件类型上传?
以下是我的尝试:
模型
public class Resume
{
[Key]
public int ResumeId { get; set; }
[StringLength(255)]
public string FileName { get; set; }
[StringLength(100)]
public string ContentType { get; set; }
public byte[] Content { get; set; }
[Display(Name = "Date Uploaded")]
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime datetime { get; set; }
}
查看文件:
@using (Html.BeginForm("Create", "Resume", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Resume</h4>
<hr />
@Html.ValidationSummary(false, "", new { @class = "text-danger" })
<div class="form-group">
@Html.Label("Upload Resume", new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" id="upload" name="uploadedResume" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
控制器操作
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Resume resume, HttpPostedFileBase uploadedResume)
{
if (ModelState.IsValid)
{
if (uploadedResume != null && uploadedResume.ContentLength > 0)
{
var tempresume = new Resume
{
FileName = System.IO.Path.GetFileName(uploadedResume.FileName),
ContentType = uploadedResume.ContentType,
datetime = System.DateTime.Now
};
using (var reader = new System.IO.BinaryReader(uploadedResume.InputStream))
{
tempresume.Content = reader.ReadBytes(uploadedResume.ContentLength);
}
_context.Resumes.Add(tempresume);
}
_context.SaveChanges();
return RedirectToAction("ResumeCenter");
}
上面的代码正在按预期工作,但我无法强力键入文件上传。我也可以使用某种Data Annotation
来限制文件上传到pdf only
。或FoolProof申请限制。