在你的控制器,你可以訪問上傳的文件爲:
if(Request.Files.Count > 0 && Request.Files[0].ContentLength > 0) {
HttpPostedFileBase postFile = Request.Files.Get(0);
string filename = GenerateUniqueFileName(postFile.FileName);
postFile.SaveAs(server.MapPath(FileDirectoryPath + filename));
}
protected virtual string GenerateUniqueFileName(string filename) {
// get the extension
string ext = Path.GetExtension(filename);
string newFileName = "";
// generate filename, until it's a unique filename
bool unique = false;
do {
Random r = new Random();
newFileName = Path.GetFileNameWithoutExtension(filename) + "_" + r.Next().ToString() + ext;
unique = !File.Exists(FileDirectoryPath + newFileName);
} while(!unique);
return newFileName;
}
的文本字段將在您的控制器動作來按通常即的Request.Form [...]。請注意,您還需要將表單上的enctype設置爲「multipart/form-data」。這聽起來像你足夠了解ASP.NET MVC做剩下的事情。還要注意,你可以在aspx視圖中聲明你的表單標籤,如果你喜歡,你可以使用更傳統的方法。
<% using(Html.BeginForm<FooController>(c => c.Submit(), FormMethod.Post, new { enctype = "multipart/form-data", @id = formId, @class = "submitItem" })) { %>
<% } %>
你讓我一半在那裏!只有一個小問題:Image1和Image2不能保證在那裏。那麼,如果用戶只提供Image2而不提供Image1呢?有沒有辦法知道它來自哪個上傳控件? – 2009-03-03 01:14:05