2009-03-03 76 views
5

我很新的ASP.net MVC的,所以請儘量在你的答案:)作爲描述上傳多張圖片+文字的ASP.NET MVC領域

讓我簡化了什麼我想做。想象一下,我有一個表單,你想輸入關於汽車的一些信息。這些字段可能是:Make,Model,Year,Image1,Image2。

窗體的底部是一個「保存」按鈕。相關的控制器方法將Image1和Image2保存到磁盤,獲取它們的文件名並將它們與汽車模​​型相關聯,然後將它們保存到數據庫中。

任何想法?

謝謝你們!

編輯

winob0t了我大部分的方式存在。唯一突出的問題是:Image1和Image2不是必填字段,所以我現在可以保存0,1或2張圖片;但如果用戶只上傳1張照片,我無法知道它是否來自imageUpload1或imageUpload2。

再次,任何幫助表示讚賞!

回答

7

在你的控制器,你可以訪問上傳的文件爲:

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" })) { %> 

<% } %> 
+0

你讓我一半在那裏!只有一個小問題:Image1和Image2不能保證在那裏。那麼,如果用戶只提供Image2而不提供Image1呢?有沒有辦法知道它來自哪個上傳控件? – 2009-03-03 01:14:05

1

這是我的解決方案,上面的答案不適合我的情況。它不關心表單細節,並且會允許多次上傳。

for (int i = (Request.Files.Count - 1); i >= 0; i--) 
    { 
      if (Request.Files != null && Request.Files[i].ContentLength > 0) 
      { 
       string path = this.Server.MapPath("~/Content/images/"); 
       string filename = Path.GetFileName(Request.Files[i].FileName); 
       string fullpath = Path.Combine(path, filename); 
       Request.Files[i].SaveAs(fullpath); 
      } 
    }