一、需求
1.需求:在Web端實現上傳圖片功能的基礎上,增加預覽圖片並裁剪圖片功能。
2.未更改之前如下圖所示:
3.更改後的功能,當點擊瀏覽(原生input type='file'控制項)選擇圖片上傳後,可以調整裁剪框大小及位置,點擊上傳按鈕實現裁剪並上傳,點擊確定後將裁剪後的圖片路徑賦值給父頁面的文章縮圖後的input。
二、實現 1.思路:使用input type='hidden'伺服器控制項接受Jcrop裁剪選框的寬高值以及四邊形選框的角座標,後台擷取這些值以及上傳圖片所在的本地路徑,通過Bitmap和Graphics類實現圖片的裁剪,然後儲存到本地指定路徑。 2.使用Jcrop.js外掛程式,外掛程式的Api介面及協助文檔在他的官方網站http://code.ciaoca.com/jquery/jcrop/ 3.下面是圖片上傳介面的代碼,這裡主要看頁面中的JavaScript代碼jcrop的使用。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UpFileBox.aspx.cs" Inherits="PublicPage_UpFileBox" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head id="Head1" runat="server"> <title>檔案上傳</title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <link href="jquery.Jcrop.min.css" rel="stylesheet" /> <script src="../artDialog/artDialog.source.js?skin=default"></script> <script src="../artDialog/plugins/iframeTools.js"></script> <script src="../artDialog/msgBox.js" type="text/javascript"></script> <script src="jquery.min.js"></script> <script src="jquery.Jcrop.min.js"></script> <script src="jquery.color.js"></script> <script type="text/javascript"> art.dialog.data('FileName', '<%=FileName %> '); art.dialog.data('FileSize', '<%=FileSize %> '); art.dialog.data('FilePath', '<%=FilePath %> '); </script></head><body style="background-color: White"> <form id="form1" runat="server"> <table border="0" cellpadding="1" cellspacing="0" style="height: 550px; width: 650px"> <tr height="350"> <td colspan="2"> <div id="imgContainer" style="width: 640px; height: 350px; border: 1px solid #c0c0c0"> <h3>點擊瀏覽按鈕,請選擇要上傳的圖片</h3> </div> <input type="hidden" name="x1" id="x1" value="" runat="server" /> <input type="hidden" name="x2" id="x2" value="" runat="server" /> <input type="hidden" name="y1" id="y1" value="" runat="server" /> <input type="hidden" name="y2" id="y2" value="" runat="server" /> <input type="hidden" name="w" id="w" value="" runat="server" /> <input type="hidden" name="h" id="h" value="" runat="server" /> </td> </tr> <tr height="30"> <tr height="30"> <td align="left"> <input id="PictureUrl" runat="server" name="File1" type="file" onchange="bindImgSrc()" /></td> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="true"> <ContentTemplate> <td width="81" align="left"> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上傳" Width="60px" CausesValidation="False" /></td> </tr> <td class="inputexplain" style="padding-left: 5px" colspan="2"> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" BackColor="#FFC0C0" BorderWidth="1px" ControlToValidate="PictureUrl" Display="Dynamic" ErrorMessage="請選擇您要上傳的檔案" SetFocusOnError="True" Width="138px"></asp:RequiredFieldValidator> <asp:Label ID="LB_PicError" runat="server" BackColor="#FFC0C0" BorderWidth="1px" ForeColor="Red" Text="檔案上傳失敗。" Visible="False" Width="343px"></asp:Label> <asp:Label ID="LB_Success" runat="server" BackColor="#C0FFFF" BorderWidth="1px" ForeColor="Teal" Text="檔案上傳成功。" Visible="False" Width="122px"></asp:Label><asp:Label ID="LB_Fail" runat="server" BackColor="#FFC0C0" BorderWidth="1px" ForeColor="Red" Text="檔案上傳失敗。" Visible="False" Width="126px"></asp:Label><br> <%=hint %></td> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="Button1" /> </Triggers> </asp:UpdatePanel> </tr> </table> </form></body></html><script type="text/javascript"> function bindImgSrc() { var path = document.forms[0].PictureUrl.value;//擷取input type='file'的路徑value $('#imgContainer').html("<img src='" + path + "' alt='Alternate Text' width='640px' height='350px' id='target' />"); cutImg(); } function cutImg() { var jcrop_api; $('#target').Jcrop({ bgFade: true, bgOpacity: .2, setSelect: [45, 55, 607, 320],//固定裁剪選框的大小 onChange: showCoords, //當裁剪選框發生改變 }, function () { jcrop_api = this; }); } function showCoords(c) { $('#x1').val(c.x);//通過<input type='hidden' runat='server'>給後台提供選框的寬高,x1、y1、x2、y2為定義選框的四個角座標,w、h為定義的寬高 $('#y1').val(c.y); $('#x2').val(c.x2); $('#y2').val(c.y2); $('#w').val(c.w); $('#h').val(c.h); };</script>
4.後台代碼接受前台圖片路徑及裁剪大小參數,實現圖片裁剪和儲存。這裡主要看UPFile()方法的處理過程。
using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using DingKit;using System.Drawing;using System.Drawing.Drawing2D;using System.Net;public partial class PublicPage_UpFileBox : System.Web.UI.Page{ public string FileName = ""; public string FileSize = ""; public string FileExp = ""; public string FileNewName = ""; public string FilePath = ""; public string hint = ""; public string UpDirKey = ""; public string UpDir = ""; public string FileType = ""; public string IsKeepOldName = ""; protected void Page_Load(object sender, EventArgs e) { UpDir = CFun.GetParam("UpDir"); FileType = CFun.GetParam("FileType"); IsKeepOldName = CFun.GetParam("IsKeepOldName"); if (!IsPostBack) { } } /// <summary> /// 檔案類型是否允許 /// </summary> /// <param name="FileExp">檔案類型</param> /// <returns>是否允許</returns> public static bool IsExpAllow(string File_Exp,string FileExp) { string[] Arr_FileExp; Char[] split = { '|', ',',',' }; Arr_FileExp = File_Exp.Split(split, 100); //擷取目前的目錄下的檔案 foreach (string file in Arr_FileExp) { if (file.ToLower() == FileExp.ToLower()) return true; } return false; } /// <summary> /// 上傳圖片 /// </summary> /// <returns></returns> private bool UPFile() { if (PictureUrl.PostedFile.ContentLength == 0) { LB_PicError.Text = "上傳路徑不可為空。"; LB_PicError.Visible = true; return false; } else { LB_PicError.Visible = false; string strfilePath = PictureUrl.PostedFile.FileName; //取得檔案名稱(抱括路徑)裡最後一個"."的索引 FileExp = CFile.GetFileExp(strfilePath); FileName = CFile.GetFileName(strfilePath); //判斷檔案的類型是否是允許 if (FileType == "") { if (CFile.IsExpAllow(FileExp) == false) { LB_PicError.Text = "上傳失敗,圖片格式必須是:" + CFile.File_Exp; LB_PicError.Visible = true; return false; } } else { if (IsExpAllow(FileType,FileExp) == false) { LB_PicError.Text = "上傳失敗,檔案格式必須是:" + FileType; LB_PicError.Visible = true; return false; } } double size = PictureUrl.PostedFile.ContentLength / 1024.0; FileSize = size.ToString(); if (CFile.IsSizeAllow(PictureUrl.PostedFile.ContentLength.ToString()) == false) { LB_PicError.Text = "上傳失敗,您上傳的檔案大小為" + FileSize + "K,最大允許大小為:" + CFile.File_Sizem; LB_PicError.Visible = true; //CFun.JsAlerT("上傳失敗,您上傳的檔案超過系統允許範圍。"); return false; } //這裡我自動根據日期和檔案大小不同為檔案命名,確保檔案名稱不重複 DateTime now = DateTime.Now; string fName = CFun.Left(FileName, FileName.Length - 1 - FileExp.Length); if (IsKeepOldName == "1") { FileNewName = fName; } else { FileNewName = fName + "_" + now.DayOfYear.ToString() + PictureUrl.PostedFile.ContentLength.ToString(); } //注意: 我這裡用Server.MapPath()取當前檔案的絕對目錄.在asp.net裡""必須用""代替 if (UpDir == "null" || UpDir == "") { UpDir = CFile.UpDir; } if (CFun.Left(UpDir,1) == @"/") { UpDir = CFun.Right(UpDir, UpDir.Length - 1); } if (CFun.Right(UpDir,1) == @"/") { UpDir = CFun.Left(UpDir, UpDir.Length - 1); } FilePath = UpDir + "/" + FileNewName + "." + FileExp;//"/" + string fileUpDir = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "/" + UpDir; if (!System.IO.Directory.Exists(fileUpDir)) { System.IO.Directory.CreateDirectory(fileUpDir); } Bitmap b; Graphics g; int x11 = Convert.ToInt32(x1.Value); int x22 = Convert.ToInt32(x2.Value); int y11 = Convert.ToInt32(y1.Value); int y22 = Convert.ToInt32(y2.Value); int ww = Convert.ToInt32(w.Value); int hh = Convert.ToInt32(h.Value); using (System.Drawing.Image img = System.Drawing.Image.FromFile(PictureUrl.PostedFile.FileName))//Image.FromFile()的參數不能是uri格式 { b = new Bitmap(ww, hh, img.PixelFormat);//建立指定大小的Bitmap對象 b.SetResolution(img.HorizontalResolution, img.VerticalResolution);//設定解析度 g = Graphics.FromImage(b); //繪圖區域 g.InterpolationMode = InterpolationMode.HighQualityBicubic; //設定Graphics的高品質插補模式 g.PixelOffsetMode = PixelOffsetMode.Half; //設定像素便宜規則以高速鋸齒消除 g.DrawImage(img, new Rectangle(0, 0, ww, hh), new Rectangle(x11, y11, ww, hh), GraphicsUnit.Pixel);//以指定規則繪製圖片實現裁剪 img.Dispose();//釋放記憶體 } b.Save(fileUpDir + "/" + FileNewName + "." + FileExp);//Image.Save()儲存到指定檔案或流 b.Dispose(); g.Dispose(); return true; } } protected void Button1_Click(object sender, EventArgs e) { if (UPFile() == true) { LB_Success.Visible = true; LB_Fail.Visible = false; //CFun.HideSuccHint(); hint = ""; hint += "檔案名稱:<font Color=#990000>" + FileName + "</font><br>"; hint += "檔案大小:<font Color=#990000>" + FileSize + "KB</font><br>"; hint += "上傳路徑:<font Color=#990000>" + FilePath + "</font><br>"; } else { LB_Success.Visible = false; LB_Fail.Visible = true; hint = ""; hint += "檔案名稱:<font Color=#990000>" + FileName + "</font><br>"; hint += "檔案大小:<font Color=#990000>" + FileSize + "KB</font><br>"; hint += "上傳路徑:<font Color=#990000>" + FilePath + "</font><br>"; } }}
三、總結
總結一下過程中遇到的問題:
1.前台給後台傳值:可以使用input type=‘hidden’添加runat=‘server’屬性編程伺服器控制項,使用js給該控制項賦值,後台接受該控制項value;
2.後台給前台傳值:在後台定義一個public變數,前台通過js擷取該變數,例如var filepath = ‘<%=FilePath%>’;
3.後台Image.FromFile(path)參數不支援Uri格式問題:Image.FromFile(path)的path應該為本地檔案路徑,擷取的是input type='file'的value,例如PictureUrl.PostedFile.FileName
3.解決後台Image.FromFile(path)參數不支援Uri格式問題:如果你必須傳入一個url,那麼請改用Image.FromStream()方法,例如:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);WebResponse response = request.GetResponse();//獲得響應Image img = Image.FromStream(response.GetResponseStream());///執行個體化,得到img
4.儲存檔案到指定目錄方式的兩種方式:
4.1)PictureUrl.PostedFile.SaveAs(fileUpDir + "/" + FileNewName + "." + FileExp); //input id='PictureUrl' type='file' runat='server'控制項 使用SaveAs()
4.2)b.Save(fileUpDir + "/" + FileNewName + "." + FileExp);//Image.Save()儲存到指定檔案或流
5.該軟體使用了artdialog對話方塊組件,很多時候我們在接手一個新項目時,需要瞭解一下他組件的基本使用,對話方塊組件中應該包括父子頁面傳值的函數,要善於使用手頭的各種工具;
6.很多時候應該多多梳理邏輯,調試javascript指令碼要善於使用alert()和console.log()。
7.很多時候應該學會拒絕。