zl程序教程

您现在的位置是:首页 >  后端

当前栏目

asp.net MVC简单图片上传

NetASP上传MVC 简单 图片
2023-06-13 09:12:39 时间

大家好,又见面了,我是你们的朋友全栈君。

asp.net MVC简单图片上传

01、创建控制器HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace mvcTuPianShangChuang.Controllers
{ 
   
    public class HomeController : Controller
    { 
   
        // GET: Home
        public ActionResult Index()
        { 
   
            return View();
        }

        [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 uploadImgName = "/Upload/" + Guid.NewGuid().ToString() + file.FileName;
            //将上传的图片保存
            file.SaveAs(Request.MapPath(uploadImgName));
            //返回前一页
            return Content("<script>alert('上传成功!');history.go(-1);</script>");
        }

        //[HttpPost]
        //public ActionResult UploadImg()
        //{ 
   
        // if (Request.Files.Count > 0)
        // { 
   
        // HttpPostedFileBase f = Request.Files["file1"];
        // f.SaveAs(@"D:\" + f.FileName);
        // }
        // return Content("<script>alert('上传成功!');history.go(-1);</script>");
        // //return View();
        //}

    }
}

02创建视图Index.cshtml

@{ 
   
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        <form action="/home/uploadimg" method="post" enctype="multipart/form-data">
            <input type="file" name="imagesFile" />
            <input type="submit" value="submit" />
        </form>


    </div>
</body>
</html>

03创建文件夹Upload

04预览即可

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/162895.html原文链接:https://javaforall.cn