在MVC中上传文件

Roy*_*Roy 7 html c# rest model-view-controller file-upload

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

Geo*_*off 13

编辑:当你认为你已经弄明白时,你会发现有更好的方法.查看http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx

原文: 我不确定我是否100%理解您的问题,但我认为您要将文件上传到类似http:// {服务器名称}/{控制器} /上传的网址?这将实现与使用Web表单的普通文件上传完全相同.

所以你的控制器有一个名为upload的动作,看起来类似于:

//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" });
    }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我返回Json表示成功,但如果需要,您可以将其更改为xml(或任何相关的内容).