在MVC中我们可以很容易的通过File实现图片的显示以及下载等操作。
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div class="horizontal">
<div class="panel panel-heading">
通过File下载文件
</div>
<div class="panel panel-body">
<a href="@Url.Action("ImageFor",new {id="1"})">下载</a>
</div>
</div>
<div class="panel">
<div class="panel-heading">
通过FilePathResult显示图片
</div>
<div class="panel-body">
<img src="@Url.Action("ImageFor",new{id="1"})"/>
</div>
</div>
<div class="panel">
<div class="panel-heading">
通过FileContentResult显示图片
</div>
<div class="panel-body">
<img src="@Url.Action("ImageFor",new {id="2"})"/>
</div>
</div>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
namespace SportsStore.WebUI.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "首页";
return View ();
}
public ActionResult ImageFor(string id){
var filePath = Server.MapPath(string.Format("/Images/image{0}.jpg", "1"));
if (id == "1")
{
return File(filePath, "image/jpg", "meinv.jpg");
}else{
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)){
byte[] bytes = new byte[fs.Length];
fs.Read(bytes,0,bytes.Length);
var fileContentResult = new FileContentResult(bytes, "image/jpg");
return fileContentResult;
}
}
}
}
}
好东西,谢谢
已审核