欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ASP.NET?MVC實現(xiàn)單個圖片上傳、限制圖片格式與大小并在服務(wù)端裁剪圖片

 更新時間:2022年09月06日 08:35:02   作者:Darren?Ji  
這篇文章介紹了ASP.NET?MVC實現(xiàn)單個圖片上傳、限制圖片格式與大小并在服務(wù)端裁剪圖片的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

本篇,在ASP.NET MVC4下實現(xiàn)單個圖片上傳,具體功能包括:

  • 1、在客戶端選擇圖片,并限制圖片的大小和格式
  • 2、在客戶端上傳圖片,并顯示預(yù)覽圖
  • 3、在服務(wù)端限制圖片的大小和格式
  • 4、在服務(wù)端保存圖片時,把圖片裁剪成某個固定尺寸

本篇源碼在:https://github.com/darrenji/FileUploadInMVC

實現(xiàn)的大致思路是:

  • 客戶端限制圖片大小和格式,通過寫一個jQuery插件來實現(xiàn)
  • 服務(wù)端實現(xiàn)圖片裁剪,通過使用ImageSize組件來實現(xiàn)

首先是一個用來承載上傳信息的類:

    public class UploadFileResult
    {
        //帶后綴的名稱,比如xxx.jpg
        public string FileName { get; set; }
        //圖片的字節(jié)數(shù)
        public int Length { get; set; }
        //圖片的類型:image/jpeg
        public string Type { get; set; }
        public bool IsValid { get; set; }
        public string Message { get; set; }
        //圖片的完整路徑:~/AjaxUpload/20141112_large.jpg
        public string FilePath { get; set; }
    }

在HomeController中,需要提供一個接收前端上傳文件并返回json格式的Action方法,還需要提供一個根據(jù)文件名刪除圖片的Action方法。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ImageResizer;
using MvcApplication10.Models;
namespace MvcApplication10.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        //接收上傳圖片
        [HttpPost]
        public ActionResult UploadFile()
        {
            //允許的圖片格式
            var allowedExtensions = new[] { ".png", ".gif", ".jpg", ".jpeg" };
            //返回給前臺的結(jié)果,最終以json返回
            List<UploadFileResult> results = new List<UploadFileResult>();
            //遍歷從前臺傳遞而來的文件
            foreach (string file in Request.Files)
            {
                //把每個文件轉(zhuǎn)換成HttpPostedFileBase
                HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                //如果前臺傳來的文件為null,繼續(xù)遍歷其它文件
                if (hpf.ContentLength == 0 || hpf == null)
                {
                    continue;
                }
                else
                {
                    if (hpf.ContentLength > 1024*1024) //如果大于規(guī)定最大尺寸
                    {
                        results.Add(new UploadFileResult()
                        {
                            FileName = "",
                            FilePath = "",
                            IsValid = false,
                            Length = hpf.ContentLength,
                            Message = "圖片尺寸不能超過1024KB",
                            Type = hpf.ContentType
                        });
                    }
                    else
                    {
                        var extension = Path.GetExtension(hpf.FileName);
                        if (!allowedExtensions.Contains(extension))//如果文件的后綴名不包含在規(guī)定的后綴數(shù)組中
                        {
                            results.Add(new UploadFileResult()
                            {
                                FileName = "",
                                FilePath = "",
                                IsValid = false,
                                Length = hpf.ContentLength,
                                Message = "圖片格式必須是png、gif、jpg或jpeg",
                                Type = hpf.ContentType
                            });
                        }
                        else
                        {
                            //給上傳文件改名
                            string date = DateTime.Now.ToString("yyyyMMddhhmmss");
                            //目標文件夾的相對路徑 ImageSize需要的格式
                            string pathForSaving = Server.MapPath("~/AjaxUpload/");
                            //目標文件夾的相對路徑 統(tǒng)計文件夾大小需要的格式
                            string pathForSaving1 = Server.MapPath("~/AjaxUpload");
                            //在根目錄下創(chuàng)建目標文件夾AjaxUpload
                            if (this.CreateFolderIfNeeded(pathForSaving))
                            {
                                //保存小圖
                                var versions = new Dictionary<string, string>();
                                versions.Add("_small", "maxwidth=400&maxheight=250&format=jpg");
                                //versions.Add("_medium", "maxwidth=200&maxheight=200&format=jpg");
                                //versions.Add("_large", "maxwidth=600&maxheight=600&format=jpg");
                                //保存各個版本的縮略圖
                                foreach (var key in versions.Keys)
                                {
                                    hpf.InputStream.Seek(0, SeekOrigin.Begin);
                                    ImageBuilder.Current.Build(new ImageJob(
                                        hpf.InputStream,
                                        pathForSaving + date + key, //不帶后綴名的圖片名稱
                                        new Instructions(versions[key]),
                                        false,//是否保留原圖
                                        true));//是否增加后綴
                                }
                                results.Add(new UploadFileResult()
                                {
                                    FileName = date + "_small" + ".jpg",
                                    FilePath = Url.Content(String.Format("~/AjaxUpload/{0}", date + "_small" + ".jpg")),
                                    IsValid = true,
                                    Length = hpf.ContentLength,
                                    Message = "上傳成功",
                                    Type = hpf.ContentType
                                });
                            }
                          
                        }
                    }
                }
            }
            return Json(new
            {
                filename = results[0].FileName,
                filepath=results[0].FilePath,
                isvalid=results[0].IsValid,
                length=results[0].Length,
                message=results[0].Message,
                type=results[0].Type
            });
        }
        //根據(jù)文件名刪除文件
        [HttpPost]
        public ActionResult DeleteFileByName(string smallname)
        {
            string pathForSaving = Server.MapPath("~/AjaxUpload");
            System.IO.File.Delete(Path.Combine(pathForSaving, smallname));
            return Json(new
            {
                msg = true
            });
        }
        //根據(jù)相對路徑在項目根路徑下創(chuàng)建文件夾
        private bool CreateFolderIfNeeded(string path)
        {
            bool result = true;
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception)
                {
                    result = false;
                }
            }
            return result;
        }
    }
}

在Home/Index.cshtml中,使用checkFileTypeAndSize.js插件來限制上傳圖片的大小和格式,使用FormData對象來接收圖片文件并傳遞給服務(wù)端,客戶端接收到服務(wù)端json數(shù)據(jù)動態(tài)創(chuàng)建表格行把預(yù)覽圖顯示出來。

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<style type="text/css">
    #msg {
        color: red;
    }
</style>
<form id="file_upload_form" method="post" enctype="multipart/form-data" action="">
    <input name="file" id="file" size="27" type="file" />
    <img src="~/images/ajax-loader.gif" id="indicator" style="display: none;" />
    <br />
    <div id="imgArea">
        <table id="tbl">
            <tbody>         
            </tbody>
        </table>
    </div>
    <div>
        <span id="msg"></span>
    </div>
</form>
@section scripts
{
    <script src="~/Scripts/checkFileTypeAndSize.js"></script>
    <script type="text/javascript">
        $(function() {
            $("#file").checkFileTypeAndSize({
                allowedExtensions: ['jpg','jpeg','gif','png'],
                maxSize: 1024, //最大允許1024KB,即1MB
                success: function () {
                    //顯示進度提示
                    $('#indicator').css("display", "block");
                    //清空提示內(nèi)容
                    $('#msg').text('');
                    if ($('#fn').text().length > 0) {
                        //刪除圖片
                        deleteImg();
                    }
                    
                    //上傳文件數(shù)據(jù)準備
                    var fd = new FormData();
                    fd.append('image', $('#file')[0].files[0]);
                    $.ajax({
                        url: '@Url.Action("UploadFile","Home")',
                        type: "POST",
                        data: fd,
                        contentType: false,
                        cache: false,
                        processData: false,
                        dataType: 'json',
                        success: function (data) {
                            //隱藏進度提示
                            $('#indicator').css("display", "none");
                            if (data.isvalid) {
                                //$('#fileTemplate').tmpl(data).appendTo('#imgArea');
                                createTableTr();
                                $('#thumb').attr('src', data.filepath);
                                $('#fn').text(data.filename);
                                
                            } else {
                                $('#msg').text(data.message);
                             }
                        }
                     });
                    
                },
                extensionerror: function () {
                    //alert('允許的格式為:jpg,jpeg,gif,png');
                    $('#msg').text('允許的格式為:jpg,jpeg,gif,png');
                    return;
                },
                sizeerror: function () {
                    //alert('最大尺寸1024KB,即1MB');
                    $('#msg').text('最大尺寸1024KB,即1MB');
                    return;
                }
            });
        });
        //刪除圖片
        function deleteImg() {
            $.ajax({
                cache: false,
                url: '@Url.Action("DeleteFileByName", "Home")',
                type: "POST",
                data: { smallname: $('#fn').text() },
                success: function (data) {
                    if (data.msg) {
                        $('#fn').parent().parent().remove();
                    }
                },
                error: function (jqXhr, textStatus, errorThrown) {
                    alert("出錯了 '" + jqXhr.status + "' (狀態(tài): '" + textStatus + "', 錯誤為: '" + errorThrown + "')");
                }
            });
        }
        //創(chuàng)建表格
        function createTableTr() {
            var table = $('#tbl');
            table.append("<tr><td><img id='thumb' /></td><td colspan='2'><span id='fn'></span></td></tr>");
        }
    </script>
}

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接

相關(guān)文章

最新評論