mvc+ef实现实现文件上传代码
时间: 2023-12-09 20:03:10 浏览: 98
以下是一个基于 ASP.NET MVC 和 Entity Framework 的文件上传示例代码:
1. 创建一个名为 FileUpload 的控制器:
```csharp
public class FileUploadController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: FileUpload
public ActionResult Index()
{
return View();
}
// POST: FileUpload/UploadFile
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
// 获取文件名和扩展名
var fileName = Path.GetFileName(file.FileName);
var fileExt = Path.GetExtension(file.FileName);
// 生成一个随机的文件名
var newFileName = Guid.NewGuid().ToString() + fileExt;
// 获取上传目录的物理路径
var uploadDir = "~/Uploads/";
var uploadPath = Server.MapPath(uploadDir);
// 如果目录不存在则创建
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
// 保存文件
file.SaveAs(Path.Combine(uploadPath, newFileName));
// 将文件信息保存到数据库
var fileInfo = new FileInfo
{
FileName = fileName,
FilePath = uploadDir + newFileName,
FileSize = file.ContentLength
};
db.FileInfos.Add(fileInfo);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
}
```
2. 创建一个名为 FileInfo 的实体类:
```csharp
public class FileInfo
{
public int Id { get; set; }
public string FileName { get; set; }
public string FilePath { get; set; }
public long FileSize { get; set; }
}
```
3. 创建一个名为 ApplicationDbContext 的上下文类:
```csharp
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext() : base("DefaultConnection")
{
}
public DbSet<FileInfo> FileInfos { get; set; }
}
```
4. 创建一个名为 Index 的视图,用于显示上传表单:
```html
@using (Html.BeginForm("UploadFile", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="上传文件" />
}
```
5. 创建一个名为 _Layout 的布局视图,用于在导航栏中添加一个文件上传链接:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("My App", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("文件上传", "Index", "FileUpload")</li>
</ul>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
```
完成上述步骤后,即可在浏览器中访问 FileUpload 控制器的 Index 方法,点击文件上传链接即可上传文件,并将文件信息保存到数据库中。
阅读全文