![](/img/trans.png)
[英]How to get FileName from TextBoxFor type=file ASP.NET MVC 4?
[英]How can i get filename from input type “file” in ASP.NET MVC Project?
我是ASP.NET的新手,如果有人可以提供幫助,我將非常感激。 我有文件輸入:
<form action="NewProject.cshtml" method="post" enctype="multipart/form-data">
<fieldset>
<legend> Upload Image </legend>
<label for="Image">Image</label>
<input type="file" name="Image" id ="filename"/>
<br/>
<input type="submit" value="Upload" id="Add" />
</fieldset>
要上傳圖片,我使用:
@{ WebImage photo = null;
var newFileName = "";
var imagePath = "";
if(IsPost){
photo = WebImage.GetImageFromRequest();
if(photo != null){
newFileName = Guid.NewGuid().ToString() + "_" +
Path.GetFileName(photo.FileName);
imagePath = @"Images\" + newFileName;
photo.Save(@"~\" + imagePath);
//an attempt
PoleInvestProject.Models.Project project = new PoleInvestProject.Models.Project();
project.Image = imagePath; //storing in model property Image
}
}
}
現在,我需要從那里獲取圖像的路徑,並將其與我的模型關聯,該模型具有public string Image { get; set; }
public string Image { get; set; }
public string Image { get; set; }
。 我想通過DBContext context
將這個文件路徑存儲在數據庫DBContext context
。
context.Projects.Add(new Project()
{
Image = model.Image
});
context.SaveChanges();
但這給了我NULL,我的數據庫表中沒有Projects
。 我究竟做錯了什么? 提前致謝!
通過string的值在模型中創建一個新屬性,並將其命名為FileName。 現在,在您的視圖中,創建一個具有相同名稱的隱藏文件
<input type="hidden" id="FileName" value="" />
向文件輸入添加更改句柄
<input type="file" onchange="document.getElementById('FileName').value = this.value;" />
每次更改時,都應使用文件名的值來更新隱藏文件。 當您進行回發時,模型聯編程序將完成其余工作,並且您將在model.FileName中擁有文件名。
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.