//File upload uses the IformFile interface
1.1 file upload view
<form action="/stu/upload" method="post" enctype="multipart/form-data">
<input type="file" name="img" />
<input type="submit" value="上传" />
</form>
1.2 File upload backend code
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 Operation effect
2.1 Download file view
@Html.ActionLink("下载","downloadImg")
2.2 Back-end code (I wrote this to death, the actual project is to pass the parameters of the downloaded image from the front-end to the back-end)
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 Preview picture view
<img src="@Url.Action("GetImage", "stu", new { imageName = "4.jpg" })" alt="Image Preview">
<style>
img{
width:300px;
height:400px;
}
</style>
3.2 Backend code
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");
}
running result