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);
        }

最后显示的效果如下:

这一节貌似讲的有点乱,因为步骤有点多,而且需要实现和注意的地方不少,下面附上源码,有助于大家研究,有问题可以留言一起讨论:

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

时间: 2024-08-02 02:40:17

MVC图片上传并显示缩略图的相关文章

spring mvc 图片上传,图片压缩、跨域解决、 按天生成目录 ,删除,限制为图片代码等相关配置

spring mvc 图片上传,跨域解决 按天生成目录 ,删除,限制为图片代码,等相关配置 fs.root=data/ #fs.root=/home/dev/fs/ #fs.root=D:/fs/ #fs.domains=182=http://172.16.100.182:18080,localhost=http://localhost:8080 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE be

spring mvc 图片上传,图片压缩、跨域解决、 按天生成文件夹 ,删除,限制为图片代码等相关配置

spring mvc 图片上传,跨域解决 按天生成文件夹 ,删除,限制为图片代码,等相关配置 fs.root=data/ #fs.root=/home/dev/fs/ #fs.root=D:/fs/ #fs.domains=182=http://172.16.100.182:18080,localhost=http://localhost:8080 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE b

图片上传即时显示javascript代码

1.首先是javascript代码 /** * 图片上传即时显示javascript */ var allowExt = [ 'jpg', 'gif', 'bmp', 'png', 'jpeg' ]; var preivew = function(file, container) { try { var pic = new Picture(file, container); } catch (e) { alert(e); } }; // 缩略图类定义 var Picture = function

【Servlet】利用Servlet3.0标准与JSTL表达式实现文件上传系统,支持图片上传后显示

伴随着JDK1.6一起出现的Servlet3.0标准,使得JSP的文件上传系统不再艰难,此前在JSP的文件上传系统需要<[Jsp]使用jspsmartupload完成简单的文件上传系统>(点击打开链接)类似这样的插件才能完成的文件上传系统,还不支持中文,使得各位程序猿掏空心思才能解决这个问题.现在Servlet3.0对文件上传的方法进行封装,无须分块就可以实现.而且Servlet3.0还不用类似<[Servlet]最简单的Servlet JavaWeb程序>(点击打开链接)在web

图片上传及显示(包含多文件)

前一段时间用到文件上传,好久没有写这个东西,有的东西也忘记了.所以本篇博客BZ决定记载一下,一方面自己回顾加深一下,另一方面供各位程序员学习. 希望大神们对本文不对的地方进行批评指正! 先在我们的html页面写上上传文件的文本框及图片显示所在的DIV,如下: 1 <div class="form-group"> 2 <label class="col-sm-2 control-label no-padding-right" id="lb_

android自定义View实现图片上传进度显示(仿手机QQ上传效果)

首先看下我们想要实现的效果如下图(qq聊天中发送图片时的效果): 再看一下我实现的效果: 1.效果已经看见了,下面我们来实现它.首先我创建一个android工程ProgressImageView.然后我们重写ImageView控件,创建ProcessImageView类代码如下: package com.example.processimageview; import android.annotation.SuppressLint; import android.content.Context;

经典的图片上传并绘制缩略图的类的代码

首先我们有3个文件 1个文件夹 images文件夹是默认存储图片地址 index.php是主页面 fileupload.class.php是图片上传类 ResizeImage.class.php是图片缩略图类 fileupload.class.php代码如下: <?php /** * file: fileupload.class.php 文件上传类FileUpload * 本类的实例对象用于处理上传文件,可以上传一个文件,也可同时处理多个文件上传 */ class FileUpload { pr

.Net MVC 图片上传

该案例是mvc下的demo,支持单张图片上传. 1 public ActionResult Upload() 2 { 3 string imgurl = ""; 4 foreach (string key in Request.Files) 5 { 6 //这里只测试上传第一张图片file[0] 7 HttpPostedFileBase file0 = Request.Files[key]; 8 9 //转换成byte,读取图片MIME类型 10 Stream stream; 11 i

node.js实现图片上传(包含缩略图)

图片上传 使用multiparty插件实现上传 安装multiparty npm i --save multiparty 代码实现 const multiparty = require('multiparty'); let form = new multiparty.Form({uploadDir: upload.path}); 构造参数说明 encoding 设置接收数据编码,默认是utf-8 maxFieldsSize 限制字段可以分配的内存量,默认2M maxFields 限制在发出错误事