用MVC實現簡單的檔案(圖片)上傳下載功能
一 實現效果簡單說明
上傳:上傳圖片,將圖片儲存到伺服器,並將相關資訊寫入資料庫。
下載:在頁面展示圖片下載列表的縮圖,點選圖片將其載入到本地。
二.View Index中程式碼
<h2>圖片上傳區</h2>
<hr/>
<div>
<!--建立表單-->
<formenctype="multipart/form-data"method="post">
<!--此處為擴充套件方法,跟直接寫input 標籤一樣的效果,引數為標籤型別,id,name,value,style-->
@Html.Raw(Html.GetInputTag(
@Html.Raw(Html.GetInputTag("submit", "submit", "submit","點選上傳",""))
</form>
<spanid="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)
{
<ahref="@Url.Action("Index","Down")?url=@item.Value"><imgsrc="@item.Key"/></a>
}
}
</div>
三.Controller homeController中程式碼
publicActionResult 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 = newEFContext();
PicFile pic = newPicFile() {
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>
publicvoid LoadPic() {
//載入圖片
EFContext context1 = newEFContext();
Dictionary<string,string> dic=newDictionary<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 中程式碼
publicActionResult 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");
}
五其他涉及的類
//製作縮圖
publicclassPictureHelper
{
///<summary>
/// 建立縮圖
///</summary>
///<param name="stream"></param>
///<returns></returns>
publicstaticvoid GetSmallPic(HttpPostedFileBase file, string smallPicPath)
{
//根據圖片流獲取圖片
using (Image img=newBitmap(file.InputStream))
{
int bigWidth = img.Width;
int bigHeight = img.Height;
//設定新圖片的寬高
int smallWidth = 150;
int smallHeight = (int)(bigHeight * 1.0 /bigWidth *smallWidth);
//建立畫布
using (Image map=newBitmap (smallWidth,smallHeight))
{
//建立畫筆
using (Graphics g=Graphics.FromImage(map))
{
//將大圖畫在畫布上
g.DrawImage(img, newRectangle(0, 0, smallHeight, smallHeight), newRectangle(0, 0, bigWidth, bigHeight), GraphicsUnit.Pixel);
}
//將小圖片儲存
map.Save(smallPicPath);
}
}
}
}
///<summary>
/// HtmlHelper擴充套件
///</summary>
publicstaticclassMyHtmlHelper
{
///<summary>
/// 生成Input標籤的擴充套件方法
///</summary>
///<param name="helper">待擴充套件的類的物件</param>
///<param name="typeName">標籤型別</param>
///<param name="id">標籤id</param>
///<param name="name">標籤name</param>
///<returns>標籤字串</returns>
publicstaticstring GetInputTag(thisHtmlHelper helper,string typeName,string id,string name,string value,string style) {
returnstring.Format("<input type='{0}' id='{1}' name='{2}' value='{3}' style='{4}'/>", typeName, id, name,value,style);
}
}