如何使用html输入文件控件上传文件? [英] How can I upload a file using html input file control?
本文介绍了如何使用html输入文件控件上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用html输入文件控件上传文件?
How can I upload a file using html input file control?
推荐答案
首先创建一个包含文件输入的HTML表单:
@using(Html.BeginForm(Index,Home,FormMethod.Post,new {enctype =multipart / form-data}))
$
}
然后添加一个控制器处理上传 -
公共类HomeController:Controller
{
//此操作呈现表单
公共ActionResult索引()
{
返回查看();
}
//此操作处理表单POST和上传
[HttpPost]
公共ActionResult索引(HttpPostedFileBase文件)
{
//确认用户选择了一个文件
if(file!= null&& file.ContentLength> 0)
{
//只提取fielname
var fileName = Path.GetFileName(file.FileName);
//将文件存储在里面〜 / app_Data / uploads文件夹
var path = Path.Combine(Server.MapPath(〜/ App_Data / uploads),fileName);
file.SaveAs(path) ;
}
//重定向回索引动作再次显示表格
返回RedirectToAction(Index);
}
}
Start by creating an HTML form which would contain a file input:
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
}
And then add a controller to handle the upload-
public class HomeController : Controller
{
// This action renders the form
public ActionResult Index()
{
return View();
}
// This action handles the form POST and the upload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
}
这篇关于如何使用html输入文件控件上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文