1.在项目中创建一个“Images”文件夹?
?2.在HomeController.cs中找到Index.cshtml视图页:输入以下代码:前台代码
//action="/Student/UploadImg" 是路径:控制器/方法名
<form action="/Student/UploadImg" method="post" enctype="multipart/form-data">
<input type="file" name="imagesFile" id="imagesFile" />
<input type="submit" value="上传" />
</form>
3.?在HomeController.cs创建UploadImg()方法:后台代码
/// <summary>
/// 图片上传
/// </summary>
/// <returns></returns>
[HttpPost]
public ActionResult UploadImg()
{
//接收表单传递过来的图片
HttpPostedFileBase file = Request.Files["imagesFile"];
//拿到文件的扩展名
string extName = System.IO.Path.GetExtension(file.FileName);
if (extName != ".jpeg" && extName != ".gif" && extName != ".jpg" && extName != ".png")
{
//返回前一页
return Content("<script>alert('文件格式不合适,请重新上传');history.go(-1);</script>");
}
//最终上传路径
string imgname = "~/images/" + file.FileName;
//将上传的图片保存
file.SaveAs(Server.MapPath(imgname));
//返回前一页
return Content("<script>alert('上传成功!');history.go(-1);</script>");
}
4.运行后点击Imzges文件夹—在文件资源管理器中打开文件夹:查看图片上传是否成功;
?
|