MVC圖片上傳並顯示縮略圖


前面已經說了怎么通過MVC來上傳文件,那么這次就說說如何上傳圖片然后顯示縮略圖,這個的實用性還是比較大。用UpLoad文件夾來保存上傳的圖片,而Temp文件夾來保存縮略圖,前面文件上傳部分就不再重復了,不過圖片上傳當然只能是圖片格式的文件,因此在之前那篇博客中 通過控制格式的上傳便能防止惡意上傳,這個是文件上傳的教程鏈接:http://www.cnblogs.com/xmfdsh/p/3988868.html

對於數據庫的設計的話就隨便點:

捕獲

於是用EF便自動生成了類如下:

public partial class Image
    {
        public int Id { get; set; }
        public string ImgName { get; set; }
        public string ImgSize { get; set; }
        public System.DateTime UpLoadTime { get; set; }
    }

下面是縮略圖產生的函數:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace UpLoadImg.Utilities
{
    public class Thumbnail
    {
        public static void CreateThumbnail(string source,string destination,int maxWidth,int maxHeight)
        {
            System.Drawing.Image Img = System.Drawing.Image.FromFile(source);
            int Width = Img.Width;
            int Height = Img.Height;
            int thumbnailWidth, thumbnailHeight;

            Resize(Width, Height, maxWidth, maxHeight, out thumbnailWidth, out thumbnailHeight);

            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(thumbnailWidth, thumbnailHeight);
            System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);

            graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            graphics.DrawImage(Img, 0, 0, thumbnailWidth, thumbnailHeight);
            bitmap.Save(destination);
        }

        private static void Resize(int Width,int Height,int maxWidth,int maxHeight,out int sizedWidth,out int sizedHeight)
        {
            if(Width<maxWidth && Height<maxHeight)
            {
                sizedWidth=Width;
                sizedHeight=Height;
                return ;
            }
            sizedWidth = maxWidth;
            sizedHeight = (int)((double)Height / Width * sizedWidth + 0.5);
            if(sizedHeight>maxHeight)
            {
                sizedHeight = maxHeight;
                sizedWidth = (int)((double)Width / Height * sizedHeight + 0.5);
            }
        }
    }
}

這種縮略圖的函數網上一搜一大把,不過實現起來也不難,就像上面那樣,我就不寫注釋,不過應該想看懂難度還是不大的。

先說上傳的過程,和上次是一樣的,只不過這次需要在數據庫中保存一些數據,因此上傳后到了服務端便要對數據進行存儲處理:

[HttpPost]
        public ContentResult UpLoadFile(HttpPostedFileBase fileData)
        {
            if (fileData != null && fileData.ContentLength > 0)
            {
                string fileSave = Server.MapPath("~/UpLoad/");
                int size = fileData.ContentLength;
                //獲取文件的擴展名
                string extName = Path.GetExtension(fileData.FileName);
                //得到一個新的文件名稱
                string newName = Guid.NewGuid().ToString() + extName;
                //給模型賦值
                Image img = new Image();
                img.ImgName = newName;
                img.ImgSize = size.ToString() ;
                img.UpLoadTime = System.DateTime.Now;
                //保存圖片的同時,保存images的數據的數據庫
                MVCEntities db = new MVCEntities();
                db.Images.Add(img);
                db.SaveChanges();

                fileData.SaveAs(Path.Combine(fileSave, newName));
            }
            return Content("");
        }

 

保存圖片的同時,保持images的數據到數據庫。

Home中的視圖便是用來顯示保存所有已經保存的圖片:html視圖如下

<body>
    <div>
        <table class="table" style="border-collapse: collapse; width: 60%;">
            <thead>
                <tr>
                    <th style="border: 1px solid #0094ff;">ID</th>
                    <th style="border: 1px solid #0094ff;">Photo</th>
                    <th style="border: 1px solid #0094ff;">FileName</th>
                    <th style="border: 1px solid #0094ff;">Size</th>
                    <th style="border: 1px solid #0094ff;">UploadTime</th>
                </tr>
            </thead>
            <tbody id="tbody1"></tbody>
        </table>
        <div id="dialog" style="display: none;" title="Dialog Title">
        </div>
    </div>
</body>

然后具體的數據應該通過js動態來加載:

//html加載時候執行的方法
        $(document).ready(function () {
            $.ajax({
                type: 'GET',
                url: '/Home/GetAllUploadImg',//通過向這個url請求數據
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (data, textStatus) {
                    var tbody = $('#tbody1');
                    $.each(data, function (i, item) {
                        OutputData(tbody, item);//得到返回的數據后,動態加載到html中。
                    });
                }
            });
        });

通過引用jQuery UI的css和js庫來實現點擊縮略圖顯示原圖:

<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.8.24.js"></script>

而函數function OutputData(tbody, item)的實現如下:

function OutputData(tbody, item) {
            var uploadTime = new Date(parseInt(item.UpLoadTime.substr(6)));
            var uploadDate = uploadTime.getFullYear() + "-" + uploadTime.getMonth() + "-" + uploadTime.getDate();
            tbody.append("<tr>" +
                        "<td style=\"border: 1px solid #0094ff;\">" +
                           item.Id +
                        "</td>" +
                        "<td style=\"border: 1px solid #0094ff;\">" +
                            "<div id=\"DivImg" + item.Id + "\"  />" +
                        "</td>" +
                        "<td style=\"border: 1px solid #0094ff;\">" +
                            item.ImgName +
                        "</td>" +
                        "<td style=\"border: 1px solid #0094ff;\">" +
                            item.ImgSize +
                        "</td>" +
                        "<td style=\"border: 1px solid #0094ff;\">" +
                            uploadDate +
                        "</td>" +
                        "</tr>");

            var imgTag = $('#DivImg' + item.Id);

            $.get("/Home/GetThumbnailImage",
             { ImgName: item.ImgName },
             function (data) {
                 imgTag.html(data);
             });


            imgTag.click(function () {
                $("#dialog").dialog({
                    autoOpen: false,
                    position: 'center',
                    title: item.OldFileName,
                    draggable: false,
                    width: 700,
                    height: 600,
                    resizable: true,
                    modal: true,
                }).dialog("open");

                $.get("/Home/GetImage",
                            { ImgName: item.ImgName },
                            function (data) {
                                $('#dialog').html(data);
                            });
            });
        }

服務端通過GetImage方法獲取原圖:

public ContentResult GetImage(Image img)
        {
            string htmltag = htmltag = "<img id=\"img1\"  src=\"/UpLoad/" + img.ImgName + "\"/>";
            return Content(htmltag);
        }

通過GetThumbnailImage(Image img)獲取縮略圖:

public ContentResult GetThumbnailImage(Image img)
        {
            string ImgUrl = "~/UpLoad/" + img.ImgName;
            string TempImgUrl="~/Temp/"+img.ImgName;
            Thumbnail.CreateThumbnail(Server.MapPath(ImgUrl), Server.MapPath(TempImgUrl), 96, 96);

            string htmltag = htmltag = "<img id=\"img1\"  src=\"/Temp/" + img.ImgName + "\"/>";
            return Content(htmltag);
        }

最后顯示的效果如下:

QQ截圖20141019203659

這一節貌似講的有點亂,因為步驟有點多,而且需要實現和注意的地方不少,下面附上源碼,有助於大家研究,有問題可以留言一起討論:

http://files.cnblogs.com/xmfdsh/MVC%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%98%BE%E7%A4%BA%E7%BC%A9%E7%95%A5%E5%9B%BE%E5%92%8C%E5%8E%9F%E5%9B%BE.zip


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM