asp.net MVC简单图片上传

asp.net MVC简单图片上传asp.netMVC简单图片上传01、创建控制器HomeController.csusingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.Mvc;namespacemvcTuPianShangChuang.Controllers{publicclassHomeController:Controller{

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

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.net/162895.html原文链接:https://javaforall.net

(0)
上一篇 2022年7月22日 下午10:00
下一篇 2022年7月22日 下午10:00


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号