【发布时间】:2010-12-09 00:16:54
【问题描述】:
我正在尝试在 MVC 中上传文件。我在 SO 上看到的大多数解决方案是使用 webform。我不想使用它,我个人更喜欢使用流。如何在 MVC 上实现 RESTful 文件上传?谢谢!
【问题讨论】:
标签: c# html model-view-controller file-upload rest
我正在尝试在 MVC 中上传文件。我在 SO 上看到的大多数解决方案是使用 webform。我不想使用它,我个人更喜欢使用流。如何在 MVC 上实现 RESTful 文件上传?谢谢!
【问题讨论】:
标签: c# html model-view-controller file-upload rest
编辑:当你认为你已经明白了一切时,你就会意识到有更好的方法。查看http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx
原文: 我不确定我是否 100% 理解您的问题,但我假设您想将文件上传到类似于 http://{server name}/{Controller}/Upload?这将完全像使用 Web 表单的普通文件上传一样实现。
所以你的控制器有一个名为上传的动作,看起来类似于:
//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(或其他任何内容)。
【讨论】:
public ActionResult register(FormCollection collection, HttpPostedFileBase FileUpload1){
RegistrationIMG regimg = new RegistrationIMG();
string ext = Path.GetExtension(FileUpload1.FileName);
string path = Server.MapPath("~/image/");
FileUpload1.SaveAs(path + reg.email + ext);
regimg.Image = @Url.Content("~/image/" + reg.email + ext);
db.SaveChanges();}
【讨论】: