【问题标题】:File upload in MVCMVC 中的文件上传
【发布时间】:2010-12-09 00:16:54
【问题描述】:

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

【问题讨论】:

    标签: c# html model-view-controller file-upload rest


    【解决方案1】:

    编辑:当你认为你已经明白了一切时,你就会意识到有更好的方法。查看http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx

    原文: 我不确定我是否 100% 理解您的问题,但我假设您想将文件上传到类似于 http://{server name}/{Controller}/Upload?这将完全像使用 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(或其他任何内容)。

    【讨论】:

    • 而且,显然总是要确保你不只是接受用户的任何旧垃圾。最低限度的检查将是内容类型、扩展名,并在您信任它之前通过病毒扫描程序运行它。 :)
    • Vary true,ZombieSheep,您需要检查客户端在服务器端发送的所有内容,即使您已经在客户端进行了验证,但所有“生产就绪”的东西都会妨碍你试图证明的点。
    • 谢谢!但这就是我目前使用的方式。我不想在服务器上保存任何文件,因为它会污染服务器。
    • @Roy,如果您不想保存文件,请使用 // * OR * 注释后的代码
    • 好的,我会从文件中获取流。谢谢!
    【解决方案2】:
    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();}
    

    【讨论】:

      猜你喜欢
      • 2013-08-31
      • 2013-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多