ASP.NET MVC中使用uploadify上傳圖片並按照規定大小壓縮圖片

來源:互聯網
上載者:User

標籤:des   style   blog   http   io   ar   color   os   使用   

 $(document).ready(function () {                     $(‘#uploadify‘).uploadify({                onUploadSuccess: function (file, returndata, response) {                    var data = eval(‘(‘ + returndata + ‘)‘);                    if (response == true && data.Success == ‘true‘) {                        $("input[name=BACKIMG]").attr("value", data.FileName);//data.FileName為圖片儲存路徑                        $(‘#mainForm‘).submit();                    } else {                        alert(data.Message);                    }                },                ‘height‘: 20,                ‘width‘: 35,                ‘uploadLimit‘: 1,                ‘queueSizeLimit‘: 1,                ‘queueID‘: ‘fileQueue‘,                              ‘removeCompleted‘: false,                ‘auto‘: false,                ‘multi‘: false,                ‘buttonText‘: ‘瀏覽圖片‘,                ‘swf‘: ‘@Url.Content("~/Scripts/uploadify/uploadify.swf")‘,                ‘uploader‘: ‘@Url.Content("~/Scripts/uploadify/UploadAttach.ashx")‘            });

將圖片上傳到伺服器的方法為UploadAttach.ashx

 /// <summary>    /// UploadAttach 的摘要說明    /// </summary>    public class UploadAttach : IHttpHandler    {        public void ProcessRequest(HttpContext context)        {            HttpPostedFile fileData = context.Request.Files["fileData"];            string floder = context.Request["floder"];            if (fileData != null)            {                try                {                    // 檔案上傳後的儲存路徑                    string path = "~/img/";                                      string filePath = context.Server.MapPath(path);                    if (!Directory.Exists(filePath))                    {                        Directory.CreateDirectory(filePath);                    }                    string saveFileName = Guid.NewGuid().ToString() + fileData.FileName;                                    string newFilePath = filePath + saveFileName;                    fileData.SaveAs(newFilePath);                    //圖片裁切                    var thumbFilePath = newFilePath.Replace(Path.GetExtension(newFilePath),                                                            ".thumb" + Path.GetExtension(newFilePath));                    ImageKit.MakeCenterThumbnail(newFilePath, thumbFilePath, 1602, 400);                    if (File.Exists(newFilePath))                    {                        File.Delete(newFilePath);                    }                    context.Response.Write("{‘Success‘:‘true‘,‘FileName‘:‘" + saveFileName.Replace(".", ".thumb.") + "‘}");                }                catch (Exception ex)                {                    context.Response.Write("{‘Success‘:‘false‘,‘Message‘:‘"+ex.Message+"‘}");                }            }            else            {                context.Response.Write("{‘Success‘:‘false‘,‘Message‘:‘請選擇要上傳的檔案‘}");            }        }        public bool IsReusable        {            get            {                return false;            }        }    }

圖片裁剪壓縮的方法

 public static class ImageKit    {          public static bool MakeCenterThumbnail(string origPath, string destPath, int width, int height)        {            try            {                using (Image image = Image.FromFile(origPath))                {                    int originalWidth = image.Width;                    int originalHeight = image.Height;                    double ratio = Math.Max((originalWidth / (double)width < originalHeight / (double)height)                                        ? originalWidth / (double)width                                        : originalHeight / (double)height, 1);                    var cutSize = new Size((int)Math.Round(width * ratio, 0), (int)Math.Round(height * ratio, 0));                    int x = (int)Math.Round((double)(originalWidth - cutSize.Width) / 2, 0);                    int y = (int)Math.Round((double)(originalHeight - cutSize.Height) / 2, 0); ;                    var bitmap = new Bitmap(width, height);                    using (var graphics = Graphics.FromImage(bitmap))                    {                        graphics.CompositingQuality = CompositingQuality.HighQuality;                        graphics.SmoothingMode = SmoothingMode.HighQuality;                        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;                        graphics.Clear(Color.White);                        var destRect = new Rectangle(0, 0, width, height);                        var originalRect = new Rectangle(x, y, cutSize.Width, cutSize.Height);                        graphics.DrawImage(image, destRect, originalRect, GraphicsUnit.Pixel);                    }                    #region wjy20131004修改                    // 以下代碼為儲存圖片時,設定壓縮品質                    EncoderParameters encoderParams = new EncoderParameters();                    long[] quality = new long[1];                    quality[0] = 100;                    EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);                    encoderParams.Param[0] = encoderParam;                    //獲得包含有關內建映像編碼解碼器的資訊的ImageCodecInfo 對象.                    ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();                    ImageCodecInfo jpegICI = null;                    for (int i = 0;i < arrayICI.Length;i++)                    {                        if (arrayICI[i].FormatDescription.Equals("JPEG"))                        {                            jpegICI = arrayICI[i];                            //設定JPEG編碼                            break;                        }                    }                    if (jpegICI != null)                    {                        bitmap.Save(destPath, jpegICI, encoderParams);                    }                    //bitmap.Save(destPath);                    #endregion                }                return true;            }            catch            {                return false;            }        }    }

使用方法:

1,首先要添加JS引用

<script src="../../Scripts/uploadify/v3.1/jquery.uploadify-3.1.min.js" type="text/javascript"></script>
<link href="../../Scripts/uploadify/v3.1/uploadify1.css" rel="stylesheet" type="text/css" />

2,在頁面中顯示上傳附件的按鈕:

<div id="fileQueue">
</div>
<input type="file" name="uploadify" id="uploadify" />
<input type="hidden" name="BACKIMG" value=""/>

注意:隱藏控制項BACKIMG是上傳檔案的路徑,檔案上傳成功後要給它賦值,這樣在表單提交成功後才可以根據圖片路徑讀取到上傳圖片

3,如下所示Form表單   

<form id="mainForm" method="post" action=‘@Url.Action(Model.Action)‘> </form>

  提交時調用上傳圖片的方法

 function submitbut() {            var filecount = $(‘#fileQueue‘).find(‘div‘).length;            if (filecount > 0) {                $(‘#uploadify‘).uploadify(‘upload‘, ‘*‘);            } else {                $(‘#mainForm‘).submit();            }        }

 

ASP.NET MVC中使用uploadify上傳圖片並按照規定大小壓縮圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.