[英]File upload in MVC
我正在尝试在MVC中上传文件。 我在SO上看到的大多数解决方案都是使用webform。 我不想使用它,并且个人更喜欢使用流。 如何在MVC上实现RESTful文件上传? 谢谢!
编辑:当你认为你已经弄明白时,你会发现有更好的方法。 查看http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx
原文:我不确定我是否100%理解您的问题,但我认为您要将文件上传到类似http:// {服务器名称} / {控制器} /上传的网址? 这将实现与使用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(或任何相关的内容)。
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();}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.