我正在嘗試將檔案從網站上傳到我的 wwwroot/images 目錄,但有時只有一半的影像被上傳,而且它似乎不適用于 .png 檔案,這是我的代碼:
[HttpPost]
public IActionResult UploadFile(IFormFile userfile)
{
MgvaKrantransportContext DBContext = new MgvaKrantransportContext();
try
{
Image image = new Image() { Filepath = "images/" userfile.FileName, Filename = userfile.FileName };
DBContext.Add(image);
DBContext.SaveChanges();
}
catch (Exception ex)
{
ViewBag.message = ex.Message;
}
try
{
string filename = userfile.FileName;
filename = Path.GetFileName(filename);
string uploadFilePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images", filename);
var stream = new FileStream(uploadFilePath, FileMode.Create);
userfile.CopyToAsync(stream);
ViewBag.message = "Success";
}
catch (Exception ex)
{
ViewBag.message = ex.Message;
}
return RedirectToAction("Index");
}
這是視圖中的表單:
@using (Html.BeginForm("UploadFile", "Management", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<h2>Upload File</h2>
<input type="file" name="userfile">
<br />
<input type="submit" value="Upload" />
}
預先感謝!最好的問候馬克斯
uj5u.com熱心網友回復:
該CopyToAsync方法回傳一個為成功復制Task必須編輯的。await您的代碼當前正在復制完成之前關閉目標流。
要么更改您的代碼以使用同步CopyTo方法,要么制作您的操作方法async和await任務。
在將名稱保存到資料庫之前,您還需要從 中洗掉任何目錄資訊FileName- 您在構建物理路徑時已經完成,但不是針對Image物體。
并添加await using到DbContext和FileStream實體以確保它們始終被正確處理。
ViewBag如果您要回傳重定向,則在中存盤值是沒有意義的;這些價值觀將永遠丟失。您可以TempData改用,它將訊息存盤在會話中。
而且Directory.GetCurrentDirectory()并不是真正獲得應用程式根路徑的最佳方式。相反,注入服務IWebHostEnvironment并使用其WebRootPath屬性來查找檔案夾的物理路徑wwwroot。
[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile userfile)
{
await using MgvaKrantransportContext DBContext = new MgvaKrantransportContext();
try
{
string filename = userfile.FileName;
filename = Path.GetFileName(filename);
Image image = new()
{
Filepath = "images/" filename,
Filename = filename
};
await DBContext.AddAsync(image);
await DBContext.SaveChangesAsync();
string uploadFilePath = Path.Combine(WebHost.WebRootPath, "images", filename);
await using var stream = new FileStream(uploadFilePath, FileMode.Create);
await userfile.CopyToAsync(stream);
}
catch (Exception ex)
{
// TODO: Log the error somewhere
}
return RedirectToAction("Index");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/422410.html
標籤:
