mvc+ef实现实现文件上传代码
时间: 2023-12-09 22:03:10 浏览: 83
下面是一个基于MVC和EF的文件上传代码示例:
1. 在MVC中创建一个上传文件的视图(View)和控制器(Controller):
View代码:
```html
@using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="Upload" />
}
```
Controller代码:
```csharp
public class HomeController : Controller
{
private readonly ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile file)
{
if (file == null || file.Length == 0)
return Content("file not selected");
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\uploads", file.FileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
var fileModel = new FileModel()
{
FileName = file.FileName,
FilePath = filePath
};
_context.FileModels.Add(fileModel);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
```
2. 创建一个FileModel类作为上传的文件记录,用于在数据库中存储上传的文件信息:
```csharp
public class FileModel
{
public int Id { get; set; }
public string FileName { get; set; }
public string FilePath { get; set; }
}
```
3. 在EF中创建一个DBContext类(ApplicationDbContext),用于连接数据库并映射FileModel类:
```csharp
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<FileModel> FileModels { get; set; }
}
```
4. 在Startup类中配置数据库连接和EF:
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllersWithViews();
}
```
5. 在appsettings.json文件中添加数据库连接字符串:
```json
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=FileUploadDb;Trusted_Connection=True;MultipleActiveResultSets=true"
}
```
6. 最后,在wwwroot目录下创建一个uploads文件夹,用于保存上传的文件。
这样,当用户选择文件并点击“Upload”按钮时,文件将被保存在服务器上,并在数据库中创建一个新的FileModel记录。
阅读全文