实现简单的文件上传,整体测试如下:
1.一个简单的前端界面,
2.选择文件后点击打开
3.点击上传后文件就会保存到目标存储路径位置
具体效果就是这样,话不多说,直接上代码
1.创建好MVC项目后,找到Controllers文件右键添加控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Demo_File.Controllers
{
public class FiledController : Controller
{
// GET: Filed
public ActionResult Upload()
{
return View();
}
[HttpPost]//表单的提交为Post方式,必须加上
public ActionResult Upload(HttpPostedFileBase file)
{
if (file!=null)//如果文件不为空进入判断
{
if (file.ContentLength==0)//如果文件长度是0,也就是没有文件的话
{
return View();//返回视图
}
else
{
//否则就保存已经上传成功的文件到目标文件夹里
file.SaveAs(Server.MapPath("~/UploadFile/" + file.FileName));
}
}
return View();
}
}
}
注意:UploadFile是你的文件夹名字,必须要存在,所以要先建立好文件夹,也可以使用代码判断进行创建 ,这里为了方便直接找到项目右键添加文件夹就好
代码都完成后 鼠标悬浮到Upload上右键添加视图,进入前端视图页
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Upload</title>
</head>
<body>
<h1>文件上传</h1>
@*action指所提交表单需要处理的路径
method则表示表单的提交方式 post
enctype表示这个地方需要传递我们的文件*@
<form action="/Filed/Upload" method="post" enctype="multipart/form-data">
<h3>选择上传的文件:</h3><input type="file" name="file" id="file" />
<br />
<br />
<input type="submit" name="submit1" value="上传" />
</form>
</body>
</html>
写好以上代码即可。