文件上传在MVC [英] File upload in MVC
问题描述
我想在MVC上传文件。我看到的大多数解决方案,以便为使用网络表单。我不希望使用和personly更喜欢使用流。你如何MVC实现REST风格的文件上传? !谢谢
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/上传档案与 - 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%,但我认为你要上传文件到一个URL,看起来像HTTP:// {服务器名称} / {}控制器/上传?这将被精确地实现像使用Web表单一个正常的文件上传
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.
所以,你的控制有一个名为上传操作,看起来与此类似:
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屋!