我正在尝试在 MVC 中上传文件。我在 SO 上看到的大多数解决方案是使用 webform。我不想使用它并且个人更喜欢使用流。你如何在 MVC 上实现 RESTful 文件上传?谢谢!
最佳答案
编辑:就在您认为自己已经弄清楚了所有问题时,您意识到有更好的方法。查看http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx
原文: 我不确定我是否 100% 理解您的问题,但我假设您想将文件上传到类似于 http://{server name}/{Controller}/Upload?这将完全像使用 Web 表单上传普通文件一样实现。
所以你的 Controller 有一个名为上传的 Action ,看起来类似于:
//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(或与此相关的任何内容)。
关于c# - MVC中的文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1605766/