MVC中的文件上传 [英] File upload in MVC

查看:18
本文介绍了MVC中的文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to upload files within MVC. Most solution I saw on SO is use webform. I don't want to use that and personly prefer using streams. How do you implement RESTful file uploading on MVC? Thanks!

推荐答案

就在您认为已经解决了所有问题时,您意识到还有更好的方法.查看 http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx

And just when you think you have it all figured out you realise that there is a better way. Check out http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx

原文:我不确定我是否 100% 理解您的问题,但我假设您想将文件上传到类似于 http://{server name}/{Controller}/Upload?这将与使用网络表单的普通文件上传完全一样.

Original: I am not sure that I understand your question 100%, but I assume that you want to upload a file to a url that looks something like http://{server name}/{Controller}/Upload? This would be implemented exactly like a normal file upload using web forms.

所以你的控制器有一个名为 upload 的动作,看起来像这样:

So your controller has an action named upload and looks similar to this:

//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(或任何与此相关的内容).

In this case I am returning Json to indicate success, but you can change this to xml (or anything for that matter) if needed.

这篇关于MVC中的文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆