//ファイルのアップロードは 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");
}
実行結果