一 实现效果简单说明
上传:上传图片,将图片保存到服务器,并将相关信息写入数据库。
下载:在页面展示图片下载列表的缩略图,点击图片将其加载到本地。
二.View Index中代码
<h2>图片上传区</h2>
<hr />
<div>
<!--创建表单-->
<form enctype="multipart/form-data" method="post">
<!--此处为扩展方法,跟直接写input 标签一样的效果,参数为标签类型,id,name,value,style-->
@Html.Raw(Html.GetInputTag("file", "upFile", "upFile","",""))<br /><br /><br />
@Html.Raw(Html.GetInputTag("submit", "submit", "submit","点击上传",""))
</form>
<span id="spShowMsg">@ViewData["ShowMsg"]</span>
</div>
<hr />
<div>
<h2>图片下载列表</h2><!--后台设置将图片路径保存在了ViewBag.Tag中-->
@if (ViewBag.Tag!=null&&ViewBag.Tag.Count > 0)
{
foreach (KeyValuePair<string,string> item in ViewBag.Tag)
{
<a href="@Url.Action("Index","Down")?url=@item.Value"><img src="@item.Key"/></a>
}
}
</div>
三.Controller homeController中代码
public ActionResult Index()
{
ViewData["ShowMsg"] = "";
//获取上传的文件
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
//获取文件名称,(考虑兼容)
string fileName = Path.GetFileName(file.FileName);
string ext = Path.GetExtension(fileName);
//判断是否为图片,可自行添加后缀名,或者用正则匹配
if (ext==".jpg"||ext==".gif")
{
//虚拟目录
string virtualPath="/PicUpAndDown/"+DateTime.Now.ToString("yyyy-MM-dd")+"/big/";
string smallVirtualPath="/PicUpAndDown/"+DateTime.Now.ToString("yyyy-MM-dd")+"/small/";
//确认是否存在虚拟目录,不存在则创建
Directory.CreateDirectory(Path.GetDirectoryName(Request.MapPath(virtualPath)));
Directory.CreateDirectory(Path.GetDirectoryName(Request.MapPath(smallVirtualPath)));
//拼接存储图片的完整路径
string path =Path.Combine( Request.MapPath(virtualPath),fileName);
string smallPath = Path.Combine(Request.MapPath(smallVirtualPath), fileName);
//创建缩略图
PictureHelper.GetSmallPic(file, smallPath);
file.SaveAs(path);
//用EF将存储信息保存到数据库,数据库中存储虚拟路径+文件名便于展示
EFContext context = new EFContext();
PicFile pic = new PicFile() {
PicPath=virtualPath+fileName,
SmallPicPath=smallVirtualPath+fileName,
FullPicPath=path,
FullSmallPicPath=smallPath,
CreateTime=DateTime.Now
};
context.PicFile.Add(pic);
context.SaveChanges();
ViewData["ShowMsg"] = "图片上传成功";
//加载图片
LoadPic();
}
else
{
//不是图片
ViewData["ShowMsg"] = "请上传正确格式的图片";
LoadPic();
}
}
else
{
LoadPic();
}
return View();
}
/// <summary>
/// 加载图片
/// </summary>
public void LoadPic() {
//加载图片
EFContext context1 = new EFContext();
Dictionary<string,string> dic=new Dictionary<string,string> ();
//从数据库读取所有数据
var result = context1.PicFile.Select(picture => picture);
foreach (var item in result)
{
//添加到字典
dic[item.SmallPicPath]=Server.UrlEncode(item.FullPicPath);
}
//传递到view中
ViewBag.Tag = dic;
}
四 Controller DownController 中代码
public ActionResult Index()
{
//获取当前请求上下文
HttpContextBase context = HttpContext;
//转码成路径
string str=Server.UrlDecode(Request["url"].ToString());
//设置报文头,下载而非打开图片
context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}\"", HttpUtility.UrlEncode(str)));
//下载文件,参数2指定格式
return File(str, "image/jpeg");
}
五 其他涉及的类
//制作缩略图
public class PictureHelper
{
/// <summary>
/// 创建缩略图
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static void GetSmallPic(HttpPostedFileBase file, string smallPicPath)
{
//根据图片流获取图片
using (Image img=new Bitmap(file.InputStream))
{
int bigWidth = img.Width;
int bigHeight = img.Height;
//设定新图片的宽高
int smallWidth = 150;
int smallHeight = (int)(bigHeight * 1.0 /bigWidth *smallWidth);
//创建画布
using (Image map=new Bitmap (smallWidth,smallHeight))
{
//创建画笔
using (Graphics g=Graphics.FromImage(map))
{
//将大图画在画布上
g.DrawImage(img, new Rectangle(0, 0, smallHeight, smallHeight), new Rectangle(0, 0, bigWidth, bigHeight), GraphicsUnit.Pixel);
}
//将小图片保存
map.Save(smallPicPath);
}
}
}
}
/// <summary>
/// HtmlHelper扩展
/// </summary>
public static class MyHtmlHelper
{
/// <summary>
/// 生成Input标签的扩展方法
/// </summary>
/// <param name="helper">待扩展的类的对象</param>
/// <param name="typeName">标签类型</param>
/// <param name="id">标签id</param>
/// <param name="name">标签name</param>
/// <returns>标签字符串</returns>
public static string GetInputTag(this HtmlHelper helper,string typeName,string id,string name,string value,string style) {
return string.Format("<input type='{0}' id='{1}' name='{2}' value='{3}' style='{4}'/>", typeName, id, name,value,style);
}
}