c# - 我想在数据库中上传和下载 ASP.NET MVC 中的文件。?
问题描述
我想在 ASP.NET MVC 中上传和下载文件。
这是我在控制器中的操作方法。当我调试文件是null
. 我哪里错了?
public ActionResult UploadDocument(CompanyViewModel model,HttpPostedFileBase FileUpload)
{
var userId = User.Identity.GetUserId<int>();
if (model.File != null && model.File.ContentLength > 0)
{
string fileExtension = System.IO.Path.GetExtension(model.File.FileName);
if (fileExtension == ".doc" || fileExtension == ".docx" || fileExtension == ".xlsx" || fileExtension == ".xls" || fileExtension == ".pdf" || fileExtension == ".jpeg" || fileExtension == ".jpg")
{
var file = model.File;
var fileName = System.IO.Path.GetFileNameWithoutExtension(model.File.FileName);
var contentLength = file.ContentLength;
var contentType = file.ContentType;
var document = new CompanyDocument();
document.CreatedDate = System.DateTime.Now;
byte[] byteData = new byte[file.InputStream.Length];
file.InputStream.Read(byteData, 0, byteData.Length);
document.FileData = byteData;
document.FileName = fileName;
document.CategoryId = model.CategoryId;
document.ContentType = contentType;
document.CreatedDate = DateTime.Now;
_CompanyDocumentsRepository.AddOrUpdate(document);
}
else
{
TempData["ErrorMessage"] = "Only word, excel, pdf, jpg files are allowed to upload.";
return Json(new { msgstatus = false, msg = "Only word, excel, pdf, jpg files are allowed to upload." }, JsonRequestBehavior.AllowGet);
}
}
return Json(new { msgstatus = true, msg = "Document uploaded successfully." }, JsonRequestBehavior.AllowGet);
}
我的观点:
@model BusSchedulingSystem.Web.ViewModels.CompanyViewModel
@using(Html.BeginForm("UploadDocument","Company", null, FormMethod.Post, new { enctype="multipart/form-data"}))
{
if (Model != null && Model.Id > 0)
{
@Html.HiddenFor(m => m.Id)
}
@Html.AntiForgeryToken()
<div class="row wrapper border-bottom white-bg page-heading">
<div class="ibox float-e-margins">
<div class="row">
<div class="col-sm-6">
<h4 class="section-title">Upload File</h4>
<div class="ibox-content">
<div class="form-group">
@Html.LabelFor(m => m.FileName)
<input type='file' name="FileUpload" id="File">
<input type="submit" value="Upload" />
@Html.ValidationMessageFor(model => model.FileName, "", new { @class = "text-danger" })
</div>
<div class="form-group">
</div>
</div>
</div>
</div>
</div>
</div>
}
解决方案
推荐阅读
- flutter - 出现软键盘时底部与像素重叠
- drupal - 有没有办法在 Drupal 8 的同一页面上输入多种内容类型的数据?
- r - R加入返回所有NA
- html - 如何在锚标记的href中给出angularjs数据绑定值
- android - 片段简历:显示和隐藏交易不起作用
- sql-server - 如何根据ID上传xls文件到sql server
- java - oncreate 应用程序类中的 IllegalStateException
- php - PHP ACPu 存储作为会话持有者
- javascript - 无法在 vue webpack 项目中导入 Ace 文档对象?
- php - 如何在 php 'mg/dl' 中回显这个结果;