添加上传图片方法

在这里插入图片描述
private IWebHostEnvironment _hostEnvironment;
public ValuesController1(IWebHostEnvironment hostEnvironment)
{
_hostEnvironment = hostEnvironment;
}

    [HttpPost]
    [Route("/ValuesController1/AddFood")]
    public int AddFood(string ff)
    {
        FoodInfoModel m = JsonConvert.DeserializeObject<FoodInfoModel>(ff);
        var s = m.Food_Imgs;
        if (Request.Form.Files.Count > 0)
        {
            //获取物理路径
            string path = _hostEnvironment.ContentRootPath + "\\wwwroot\\img";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var file = Request.Form.Files[0];
            string fileExt = file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
            string filename = Guid.NewGuid().ToString() + "." + fileExt;
            string fileFullName = path + "\\" + filename;
            using (FileStream fs = System.IO.File.Create(fileFullName))
            {
                file.CopyTo(fs);
                fs.Flush();
            }
            m.Food_Imgs = "/img/" + filename;
        }
        return dal.AddImg(m);
    }
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页