我需要上傳一個圖像作爲MVC應用程序中創建動作的一部分。使用ASP.NET MVC上傳圖像
圖像將被存儲在文件服務器中,並且數據庫將包含一個路徑。
我打算使用follwing標籤來獲取文件:
> <input type="file" id="MyImage" name="MyImageName" />
如何訪問和保存該控制器的動作?
我需要上傳一個圖像作爲MVC應用程序中創建動作的一部分。使用ASP.NET MVC上傳圖像
圖像將被存儲在文件服務器中,並且數據庫將包含一個路徑。
我打算使用follwing標籤來獲取文件:
> <input type="file" id="MyImage" name="MyImageName" />
如何訪問和保存該控制器的動作?
我把這個在BaseController類,從我所有的控制器繼承:
// this just prefixes datetime as yyyyMMddhhmmss to the filename, to
// be use that no name collision will occur.
protected static String PrefixFName(String fname)
{
if (String.IsNullOrEmpty(fname))
{
return null;
}
else
{
return String.Format("{0}{1}",
DateTime.Now.ToString("yyyyMMddhhmmss"),
fname);
}
}
protected String SaveFile(HttpPostedFileBase file, String path)
{
if (file != null && file.ContentLength > 0)
{
if (path == null)
{
throw new ArgumentNullException("path cannot be null");
}
String relpath = String.Format("{0}/{1}", path, PrefixFName(file.FileName));
try
{
file.SaveAs(Server.MapPath(relpath));
return relpath;
}
catch (HttpException e)
{
throw new ApplicationException("Cannot save uploaded file", e);
}
}
return null;
}
然後,在控制我做的:
savedPath = SaveFile(Request.Files["logo"], somepath);
在你的控制器動作應該出來
Action(HttpPostedFileBase MyImageName) {
etc;
}
您也可以通過Request.Files如果有必要獲得該文件。
Request.Files是空的,但我的串場爲文件名正在設置。我的觀點HTML是: 」/> – littlechris 2009-09-04 21:02:09
奇怪...什麼是返回的值?另外,爲什麼你要爲輸入標籤設置一個值attr?請注意,如果您重新運行表單,則無法重用它(例如,如果表單無效且用戶必須糾正某些內容)。 – giorgian 2009-09-05 09:09:38
對其進行排序。缺少名稱標籤,只有在視圖中的id。 :) – littlechris 2009-09-05 12:21:39