2012-04-05 54 views
0

我希望有人可以修改我的代码下面,告诉我如何得到这个做我想做的。保存图像从ASP.net MVC 3的HTML表单C#

我有一个HTML表单的帖子下列行动:

public ActionResult Create(string EntryTitle, string EntryVideo, HttpPostedFileBase ImageFile, string EntryDesc) 
    { 
     if (Session["User"] != null) 
     { 
      User currentUser = (User)Session["User"]; 

      string savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(ImageFile.FileName)); 
      ImageFile.SaveAs(savedFileName); 

      Entry newEntry = new Entry(); 

      newEntry.Title = EntryTitle; 
      newEntry.EmbedURL = EntryVideo; 
      newEntry.Description = EntryDesc; 
      newEntry.ImagePath = savedFileName; 
      newEntry.UserId = currentUser.UserId; 

      db.Entries.Add(newEntry); 
      db.SaveChanges(); 


     } 

     return RedirectToAction("MyPage", "User"); 
    } 

此图像保存到根目录的解决方案(或试图,没有权限,并抛出异常,而不是)。

我想什么它做的是以下几点:

1)验证文件的大小是在一些最大,假设500KB现在

2)假设文件大小是好的,它保存到以下目录

mywebsite.com/uploads/<userid>/<entryid>/entry-image.<jpg/png/gif> 

我不知道如何重命名文件,因为我要接受不同的文件扩展名(.JPEG,为.jpg,.png,.gif注意)。或者不确定如何把它放到上面的正确目录中。或者如何验证文件大小,因为显然你只能用javascript做到这一点,如果用户使用IE浏览器。

回答

1

1.Verify文件的大小是在一些最大,假设500KB现在

可以使用HttpPostFileBase.ContentLength属性来获取文件的大小(以字节为单位)。

if (ImageFile.ContentLength > 1024 * 500) // 1024 bytes * 500 == 500kb 
{ 
    // The file is too big. 
} 

2.Assuming文件大小是没关系,把它保存到以下目录

string savedFileName = Server.MapPath(string.Format("~/uploads/{0}/{1}/entry-image{2}", 
    currentUser.UserId, 
    newEntry.EntryId, 
    Path.GetExtension(ImageFile.FileName))); 

我看到的唯一问题是,它看起来像你的Entry.EntryId可能会在数据库中以便生成在生成之前将无法将其用作保存路径的一部分。

+0

这正是我需要的,谢谢!对于ASP.net来说很新,但是慢慢地掌握了它。 – Danny 2012-04-05 23:21:07

0

希望这有助于或至少指向你在正确的方向

if (ImageFile.ContentLength < 1024 * 500) 
      { 
       Entry newEntry = new Entry(); 

       newEntry.Title = EntryTitle; 
       newEntry.EmbedURL = EntryVideo; 
       newEntry.Description = EntryDesc; 
       newEntry.UserId = currentUser.UserId; 

       db.Entries.Add(newEntry); 
       db.SaveChanges(); //this helps generate an entry id 

       string uploadsDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "uploads"); 
       string userDir = Path.Combine(uploadsDir, <userid>); 
       string entryDir = Path.Combine(userDir, newEntry.EntryID); 

       if (Directory.Exists(userDir) == false) 
        Directory.CreateDirectory(userDir); 

       if (Directory.Exists(entryDir) == false) 
        Directory.CreateDirectory(entryDir); 

       string savedFileName = Path.Combine(entryDir, <entry-image>); 
       ImageFile.SaveAs(savedFileName); 

       newEntry.ImagePath = savedFileName; //if this doesn't work pull back out this entry and adjust the ImagePath 
       db.SaveChanges(); 

      } 

你应该授予写权限“上传”目录。

您还可以限制文件大小为你的web应用程序从web.config

<system.web> 
     <httpRuntime maxRequestLength="500"/> 
+0

我将如何授予写入权限来上传目录? – Danny 2012-04-06 00:32:35