上传指定文件夹中的图像并将路径保存在数据库.NET核心中 [英] Upload image in specified folder and save path in database .NET core

查看:113
本文介绍了上传指定文件夹中的图像并将路径保存在数据库.NET核心中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task Create([Bind]Employee employee)
        {
            if (ModelState.IsValid)
            {
                var files = HttpContext.Request.Form.Files;
                foreach (var Image in files)
                {
                    if (Image != null && Image.Length > 0)
                    {
                        var file = Image;

                        var uploads = Path.Combine(_appEnvironment.WebRootPath, "uploads\\img");
                        if (file.Length > 0)
                        {
                            var fileName = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);
                            using (var fileStream = new FileStream(Path.Combine(uploads, fileName), FileMode.Create))
                            {
                                await file.CopyToAsync(fileStream);
                                employee.ImageName = fileName;
                            }

                        }
                    }
                }
                db.Employees.Add(employee);
                db.SaveChanges();
                return RedirectToAction("Edit", new { id = employee.Id,name=employee.FirstName});
             }
        else
        {
            var errors = ModelState.Values.SelectMany(v => v.Errors);
        }
            return View(employee);

        }





我的尝试:





What I have tried:

when i save image, image save successfully in database, but it takes full image path like this C:\Users\VIZO\Desktop\employee.jpg i dont want like this, i need to save image path somehting like this ~images\employee.jpg and in specific folder and same path should save in database, also if someone show me after saving correct path how i can view that image.

推荐答案

您好朋友使用以下功能它可能会帮助您out:



Hi friend use below function it may help you out :

public static string MapPathReverse(string fullServerPath)
    {            
        return @"~\" + fullServerPath.Replace(HttpContext.Current.Request.PhysicalApplicationPath,String.Empty);
    }





如果它没有帮助只是让我知道我会解决它。



if it does not help just do let me know i will fix it.


这篇关于上传指定文件夹中的图像并将路径保存在数据库.NET核心中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆