zoukankan      html  css  js  c++  java
  • .net core图片上传详解

    首先有一点先确认下.net core 不存在Server.MapPath这个方法所以想引用服务器根目录或者web根目录应该在controller中引入IWebHostEnvironment对象

     private readonly IWebHostEnvironment _hostingEnvironment;
            public AdvertisementsController(IWebHostEnvironment hostingEnvironment) {
                _hostingEnvironment = hostingEnvironment;
            }
    

      

    /// <summary>
            /// 上传图片
            /// </summary>
            /// <returns></returns>
            public async Task<ActionResult> Upload()
            {
                try
                {
                    IFormFileCollection files = Request.Form.Files;
                    
                    var file = files[0];
                    //获取文件名后缀
                    string extName = Path.GetExtension(file.FileName).ToLower();
                    //获取保存目录的物理路径
                    if (System.IO.Directory.Exists(_hostingEnvironment.WebRootPath + "/upload/") == false)//如果不存在就创建images文件夹
                    {
                        System.IO.Directory.CreateDirectory(_hostingEnvironment.WebRootPath + "/upload/");
                    }
                    string path = _hostingEnvironment.WebRootPath + "/upload/"; //path为某个文件夹的绝对路径,不要直接保存到数据库
                                                              //    string path = "F:\TgeoSmart\Image\";
                                                              //生成新文件的名称,guid保证某一时刻内图片名唯一(文件不会被覆盖)
                    string fileNewName = Guid.NewGuid().ToString();
                    string ImageUrl = path + fileNewName + extName;
                    //SaveAs将文件保存到指定文件夹中
                    using (var stream = new FileStream(ImageUrl, FileMode.Create))
                    {
    
                        await file.CopyToAsync(stream);
                    }
                    
                    //此路径为相对路径,只有把相对路径保存到数据库中图片才能正确显示(不加~为相对路径)
                    string url = "\upload\" + fileNewName + extName;
                    return Json(new
                    {
                        Result = true,
                        Data = url
                    });
                }
                catch (Exception exception)
                {
                    return Json(new
                    {
                        Result = false,
                        exception.Message
                    });
                }
            }
    

      

  • 相关阅读:
    Win7系统重启网卡批处理
    第一个应用程序HelloWorld
    JS异步流程控制(序列模式、并发模式、有限并发模式)
    bootstrap+MVC3在Moon.Orm中的应用(含有代码下载)
    google guava使用例子/示范
    证明Hadoop工作的正确性和可靠性只需4步图文并茂的过程
    python 图 自身遍历 及弱引用使用
    界面布局决定系统设计的成败
    .NET:栈的生长与消亡.
    IIS 6 & Server.MapPath
  • 原文地址:https://www.cnblogs.com/AndyLin/p/13396581.html
Copyright © 2011-2022 走看看