asp.net core mvc 文件上传,下载,预览

//文件上传用到了IformFile接口
1.1文件上传视图

<form action="/stu/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="img" />
    <input type="submit" value="上传" />
</form>

1.2文件上传后端代码

  private readonly IWebHostEnvironment _webHostEnvironment;

        public StuController(IWebHostEnvironment webHostEnvironment)
        {
            //使用内置的服务读取项目路径
            _webHostEnvironment = webHostEnvironment;
        }
        public IActionResult upload()
        {
            return View();
        }

        [HttpPost]
        public IActionResult upload(IFormFile img)
        {
            //返回根目录
            var contentpath = _webHostEnvironment.ContentRootPath;
            //项目跟目录下创建一个upload文件夹,存放上传的图片
            var filepath = Path.Combine(contentpath, "upload", img.FileName);
            //创建一个文件流
            using (FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.Write))
                //把上传的文件写入文件中
                img.CopyTo(fs);
            return Content("上传成功");
        }

1.3 运行效果
在这里插入图片描述
2.1下载文件视图

@Html.ActionLink("下载","downloadImg")

2.2后端代码(我这写死了,实际项目是前端传参下载图片的参数到后端)

 public byte[] GetImageBytes()
        {
            var rootpath = _webHostEnvironment.ContentRootPath;
            var filepath = Path.Combine(rootpath, "upload", "冒泡排序.png");
            string imagePath = filepath;
            byte[] imageBytes;

            try
            {
                using (FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
                {
                    using (BinaryReader br = new BinaryReader(fs))
                    {
                        imageBytes = br.ReadBytes((int)fs.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                // 处理异常
                Console.WriteLine("读取图片文件时出错:" + ex.Message);
                imageBytes = null;
            }

            return imageBytes;
        }
        public IActionResult downloadImg()
        {
            byte[] imageBytes = GetImageBytes(); // 从某处获取图片的字节数组
            string fileName = "image.jpg";
            return File(imageBytes, "image/png", fileName);
        }

3.1预览图片视图

<img src="@Url.Action("GetImage", "stu", new { imageName = "4.jpg" })" alt="Image Preview">
<style>
    img{
        width:300px;
        height:400px;
    }
</style>

3.2后端代码

 public IActionResult GetImage(string imageName)
        {
            var rootpath = _webHostEnvironment.ContentRootPath;
            var imagePath = Path.Combine(rootpath, "upload", imageName);
            var imageBytes = System.IO.File.ReadAllBytes(imagePath);
            return File(imageBytes, "image/jpeg");
        }

运行效果
asp.net core mvc 文件上传,下载,预览_第1张图片

你可能感兴趣的:(asp.net,mvc,后端)