我正在尝试在 MVC 中上传文件。我在 SO 上看到的大多数解决方案是使用 webform。我不想使用它,并且个人更喜欢使用流。如何在MVC上实现RESTful文件上传?谢谢!
Edit:当您认为自己已经解决了所有问题时,您就会意识到还有更好的方法。查看http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx
原来的:我不确定我是否 100% 理解您的问题,但我假设您想要将文件上传到类似于 http://{server name}/{Controller}/Upload? 的网址?这与使用 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" });
}
}
在本例中,我返回 Json 来指示成功,但如果需要,您可以将其更改为 xml(或任何与此相关的内容)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)