幾乎所有關于這個的教程都過時了,所以即使我找了很長時間,我也找不到任何可以回答我的查詢并且仍然有效的東西。
我有一個這樣的模型
public class
{
public int Id { get; set; }
public string Title {get;set;}
public string Author {get;set;}
}
我想為 PDF 檔案添加另一個變數。因此,用戶可以上傳每本書的 pdf 檔案,并在可能的情況下從它們下載。據我了解,類似的東西public IFormFile File { get; set; }就足夠了。我認為該視圖涉及特定的 enctypes、asp-for 等,所以這并不是我真正關心的。
我的問題是關于一個控制器,它可以做我想要的,它只為資料庫中的那個模型條目上傳一個檔案。我已經看到了一些用途DBcontext.Model.add(entryname),但通常它以我無法理解或無法作業的東西開頭。除此之外我一無所知。
uj5u.com熱心網友回復:
我在這里寫了一個關于如何上傳PDF檔案并將其保存在資料庫中的簡單演示,我在很多地方都寫了注釋,希望它可以幫助您解決您的問題。
首先,你IFormFile用來上傳檔案,但是資料庫不能直接保存這種型別的資料,所以我選擇將其轉換為byte[]然后存盤在資料庫中。
代碼:
模型
//I use this model to create a database
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public byte[] book { get; set; }
}
//Because I need data of type IFormFile to upload the file, So i create BookViewModel,
//I will use this model to pass data from view to controller
public class BookViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public IFormFile book { get; set; }
}
資料背景關系
//create the database
public class ApplicationContext : DbContext
{
public ApplicationContext(DbContextOptions<ApplicationContext> options): base(options)
{
}
public DbSet<Book> books { get; set; }
}
控制器
public class HomeController : Controller
{
//Use dependency injection to inject the database you just created into the controller
private readonly ApplicationContext _context;
public HomeController(ApplicationContext context)
{
_context = context;
}
public IActionResult UploadBook()
{
return View();
}
[HttpPost]
public async Task<IActionResult> UploadBook(BookViewModel model)
{
//Check if pdf file exists
if (model.book != null && model.book.Length>0)
{
//Instantiate Book, then assign the values ??of Author and Title in viewmode to Book
Book bookModel = new Book()
{
Author = model.Author,
Title = model.Title,
};
//Convert PDF file to byte[] and Give the byte[] to book
using (var target = new MemoryStream())
{
model.book.CopyTo(target);
bookModel.book = target.ToArray();
}
//use EF CORE and linq to add data and save .
_context.books.Add(bookModel);
_context.SaveChanges();
return RedirectToAction("Success");
}
return RedirectToAction("Fail");
}
}
看法
@model BookViewModel
<form method="post" enctype="multipart/form-data" asp-action="UploadBook">
<div >
<label asp-for="@Model.Title"></label>
<input asp-for="@Model.Title" />
</div>
<div >
<label asp-for="@Model.Author"></label>
<input asp-for="@Model.Author" />
</div>
<div >
<label asp-for="@Model.book"></label>
<input asp-for="@Model.book" />
</div>
<button type="submit">upload</button>
</form>
結果:
最后,您可以看到我已成功上傳檔案并將其保存在資料庫中。

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/464502.html
標籤:数据库 asp.net 核心 asp.net-core-mvc
上一篇:如何保持更改后的值?
