2009-10-22 78 views
7

我试图在MVC中上传文件。我在SO上看到的大多数解决方案都是使用webform。我不想使用它,并且个人喜欢使用流。你如何在MVC上实现RESTful文件上传?谢谢!MVC中的文件上传

回答

13

编辑:而当你认为你有这一切想通了,你意识到有一个更好的方法。退房http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx

原文: 我不知道,我明白你的问题100%,但我认为你要上传文件到一个URL,看起来像HTTP:// {服务器名称}/{}控制器/上传?这将与使用Web表单的正常文件上传完全相同。

所以,你的控制有一个名为上传动作,看起来与此类似:

//For MVC ver 2 use: 
[HttpPost] 
//For MVC ver 1 use: 
//[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Upload() 
{ 
    try 
    { 
     foreach (HttpPostedFile file in Request.Files) 
     { 
      //Save to a file 
      file.SaveAs(Path.Combine("C:\\File_Store\\", Path.GetFileName(file.FileName))); 

      // * OR * 
      //Use file.InputStream to access the uploaded file as a stream 
      byte[] buffer = new byte[1024]; 
      int read = file.InputStream.Read(buffer, 0, buffer.Length); 
      while (read > 0) 
      { 
       //do stuff with the buffer 
       read = file.InputStream.Read(buffer, 0, buffer.Length); 
      } 
     } 
     return Json(new { Result = "Complete" }); 
    } 
    catch (Exception) 
    { 
     return Json(new { Result = "Error" }); 
    } 
} 

在这种情况下,我回到JSON来表示成功,但你可以改变这XML(或任何为此事)如果需要的话。

+0

而且,显然总是确保你不只是接受来自用户的任何旧垃圾。在您信任它之前,最小检查将是内容类型,扩展名并通过病毒扫描程序运行。 :) – ZombieSheep 2009-10-22 08:55:15

+0

不同的是,ZombieSheep,你需要检查客户端在服务器端发送的一切,即使你已经在客户端进行了验证,但所有“生产准备”的东西阻碍了你正在尝试的点演示。 – Geoff 2009-10-22 09:05:19

+0

谢谢!但这就是我目前使用的方式。我不想在服务器上保存任何文件,因为它会污染服务器。 – Roy 2009-10-22 09:05:20

0
public ActionResult register(FormCollection collection, HttpPostedFileBase FileUpload1){ 
RegistrationIMG regimg = new RegistrationIMG(); 
string ext = Path.GetExtension(FileUpload1.FileName); 
string path = Server.MapPath("~/image/"); 
FileUpload1.SaveAs(path + reg.email + ext); 
regimg.Image = @Url.Content("~/image/" + reg.email + ext); 
db.SaveChanges();}