MVC中上传文件
与asp.net中几乎一样,使用表单提交的方式上传文件(如果是使用了第三方插件的话,那么就另当别论)
@{ ViewBag.Title = "Index"; Layout = null; } <!DOCTYPE html> <html> <head> <title>@ViewBag.Title</title> </head> <body> <form id="form1" method="post" enctype="multipart/form-data" action="@Url.Action("SaveFiles")"> <input type="file" name="file" value="" /> <br /> <input type="submit" value="提交" /> </form> </body> </html>
var path = '@Url.Action("Upload", "ControllerName")' + "?para=" + escape($('#sltor').combobox('getValue')) + "¶1=" + $('#sltor').combobox('getValue') + "¶2=" + column + "¶3=" + pointCount; var fordata = new FormData(); fordata.append('file', $('#InputUploadFile')[0].files[0]); $.ajax({ url: path, type: 'post', processData: false, contentType: false, data: fordata, success: function (res) { if (res.code == 200) { GetData(); ShowMsg('上传成功!'); } if (res.code == 400) { ShowMsg(res.msg); } }, error: function (e) { ShowMsg("认证已过期,请重新登录。"); }, headers: Obj.headers })
在vue中可以直接使用 el-upload 组件。
using System.IO;
using System.Web;
using System.Web.Mvc;
namespace PartyInvites.Controllers
{
public class UploadController : Controller
{
//
// GET: /Upload/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult SaveFiles()
{
HttpPostedFileBase file = Request.Files["file"];
if (file == null)
{
return Content("没有文件!", "text/plain");
}
var fileName = Path.Combine(Request.MapPath("~/UploadFiles"), Path.GetFileName(file.FileName));
try
{
file.SaveAs(fileName);
return Content("上传成功!", "text/plain");
}
catch
{
return Content("上传异常!","text/plain");
}
}
}
}