下面小編就為大家帶來一篇AJAX實作圖片預覽與上傳及產生縮圖的方法。小編覺得蠻不錯的,現在就分享ajax等源碼給大家,也給大家做個參考。一起跟著小編過來看看AJAX實現圖片預覽與上傳及生成縮圖的方法吧
要實現功能,上傳圖片時可以預覽,因還有別的文字,所以不只上傳圖片,實現與別的文字一起保存,當然上來先上傳圖片,然後把路徑和別的文字一起寫入資料庫;同時為圖片生成縮圖,現在只寫上傳圖片方法,文字在ajax裡直接傳參數就可以了,若要上傳多圖,修改一下就可以了。
借鑒了網路資料,自己寫了一下,並不需要再新加頁面,只在一個頁面裡就OK啦。
JS程式碼:
#//ajax保存数据,后台方法里实现此方法 function SaveData() { filename = document.getElementById("idFile").value; result =test_test_aspx.SaveData(filename).value; if (result) { alert("保存成功!"); } return false; } //实现预览功能 function DrawImage(ImgD) { var preW = 118; var preH = 118; var image = new Image(); image.src = ImgD.src; if (image.width > 0 && image.height > 0) { flag = true; if (image.width / image.height >= preW/ preH) { if (image.width > preW) { ImgD.width = preW; ImgD.height = (image.height * preW) / image.width; } else { ImgD.width = image.width; ImgD.height = image.height; } ImgD.alt = image.width + "x" + image.height; } else { if (image.height > preH) { ImgD.height = preH; ImgD.width = (image.width * preH) / image.height; } else { ImgD.width = image.width; ImgD.height = image.height; } ImgD.alt = image.width + "x" + image.height; } } } //当idFile内容改变时 function FileChange(Value) { flag = false; document.getElementById("showImg").style.display = "none"; document.getElementById("idImg").width = 10; document.getElementById("idImg").height = 10; document.getElementById("idImg").alt = ""; document.getElementById("idImg").src = Value; }
以下為前台程式碼:
<p class="cbs"> <p class="l"><label>图片:</label></p> <p> <input id="idFile" name="pic" type="file" runat="server" onchange="FileChange(this.value);" /> </p> </p> <p class="cbs"> <p class="l"><label>预览:</label></p> <p> <img src="/static/imghwm/default1.png" data-src="" alt=" class="lazy" id="idImg" style="max-width:90%" style="max-width:90%" alt="" onload="DrawImage(this);" /> //实现预览 <img id="showImg" width="118" style="max-width:90%" alt="" runat="server" style="display:none"/> //加这个主要是为了实现查看时显示图片,因为上面的(idImg)加上runat="server" 报错,如有好的方法可以留言 </p> </p>
以下為AJAX方法:
[Ajax.AjaxMethod()] public bool SaveData(string fileNamePath) { string serverFileName = ""; string sThumbFile = ""; string sSavePath = "~/Files/"; int intThumbWidth = 118; int intThumbHeight = 118; string sThumbExtension = "thumb_"; try { //获取要保存的文件信息 FileInfo file = new FileInfo(fileNamePath); //获得文件扩展名 string fileNameExt = file.Extension; //验证合法的文件 if (CheckFileExt(fileNameExt)) { //生成将要保存的随机文件名 string fileName = GetFileName() + fileNameExt; //检查保存的路径 是否有/结尾 if (sSavePath.EndsWith("/") == false) sSavePath = sSavePath + "/"; //按日期归类保存 string datePath = DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd") + "/"; if (true) { sSavePath += datePath; } //获得要保存的文件路径 serverFileName = sSavePath + fileName; //物理完整路径 string toFileFullPath = HttpContext.Current.Server.MapPath(sSavePath); //检查是否有该路径 没有就创建 if (!Directory.Exists(toFileFullPath)) { Directory.CreateDirectory(toFileFullPath); } //将要保存的完整文件名 string toFile = toFileFullPath + fileName; ///创建WebClient实例 WebClient myWebClient = new WebClient(); //设定windows网络安全认证 myWebClient.Credentials = CredentialCache.DefaultCredentials; //要上传的文件 FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read); //FileStream fs = OpenFile(); BinaryReader r = new BinaryReader(fs); //使用UploadFile方法可以用下面的格式 //myWebClient.UploadFile(toFile, "PUT",fileNamePath); byte[] postArray = r.ReadBytes((int)fs.Length); Stream postStream = myWebClient.OpenWrite(toFile, "PUT"); if (postStream.CanWrite) { postStream.Write(postArray, 0, postArray.Length); } postStream.Close(); //以上为原图 try { //原图加载 using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(serverFileName))) { //原图宽度和高度 int width = sourceImage.Width; int height = sourceImage.Height; int smallWidth; int smallHeight; //获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽 和 原图的高/缩略图的高) if (((decimal)width) / height <= ((decimal)intThumbWidth) / intThumbHeight) { smallWidth = intThumbWidth; smallHeight = intThumbWidth * height / width; } else { smallWidth = intThumbHeight * width / height; smallHeight = intThumbHeight; } //判断缩略图在当前文件夹下是否同名称文件存在 int file_append = 0; sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(fileName) + fileNameExt; while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sThumbFile))) { file_append++; sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(fileName) + file_append.ToString() + fileNameExt; } //缩略图保存的绝对路径 string smallImagePath = System.Web.HttpContext.Current.Server.MapPath(sSavePath) + sThumbFile; //新建一个图板,以最小等比例压缩大小绘制原图 using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(smallWidth, smallHeight)) { //绘制中间图 using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap)) { //高清,平滑 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.Clear(Color.Black); g.DrawImage( sourceImage, new System.Drawing.Rectangle(0, 0, smallWidth, smallHeight), new System.Drawing.Rectangle(0, 0, width, height), System.Drawing.GraphicsUnit.Pixel ); } //新建一个图板,以缩略图大小绘制中间图 using (System.Drawing.Image bitmap1 = new System.Drawing.Bitmap(intThumbWidth, intThumbHeight)) { //绘制缩略图 using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap1)) { //高清,平滑 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.Clear(Color.Black); int lwidth = (smallWidth - intThumbWidth) / 2; int bheight = (smallHeight - intThumbHeight) / 2; g.DrawImage(bitmap, new Rectangle(0, 0, intThumbWidth, intThumbHeight), lwidth, bheight, intThumbWidth,intThumbHeight, GraphicsUnit.Pixel); g.Dispose(); bitmap1.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg); return true; } } } } } catch { //出错则删除 System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(serverFileName)); return false; } } else { return false; } } catch (Exception e) { return false; } } /// <summary> /// 检查是否为合法的上传文件 /// </summary> /// <param name="_fileExt"></param> /// <returns></returns> private bool CheckFileExt(string _fileExt) { string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg" }; for (int i = 0; i < allowExt.Length; i++) { if (allowExt[i] == _fileExt) { return true; } } return false; } //生成随机数文件名 public static string GetFileName() { Random rd = new Random(); StringBuilder serial = new StringBuilder(); serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff")); serial.Append(rd.Next(0, 999999).ToString()); return serial.ToString(); }
以上就是小編為大家帶來的AJAX實現圖片預覽與上傳及生成縮圖的方法的全部內容了,希望對大家有所幫助,多多支持PHP中文網!
相關推薦:
以上是AJAX實現圖片預覽與上傳及產生縮圖的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。

是的,JavaScript的引擎核心是用C語言編寫的。 1)C語言提供了高效性能和底層控制,適合JavaScript引擎的開發。 2)以V8引擎為例,其核心用C 編寫,結合了C的效率和麵向對象特性。 3)JavaScript引擎的工作原理包括解析、編譯和執行,C語言在這些過程中發揮關鍵作用。

JavaScript是現代網站的核心,因為它增強了網頁的交互性和動態性。 1)它允許在不刷新頁面的情況下改變內容,2)通過DOMAPI操作網頁,3)支持複雜的交互效果如動畫和拖放,4)優化性能和最佳實踐提高用戶體驗。

C 和JavaScript通過WebAssembly實現互操作性。 1)C 代碼編譯成WebAssembly模塊,引入到JavaScript環境中,增強計算能力。 2)在遊戲開發中,C 處理物理引擎和圖形渲染,JavaScript負責遊戲邏輯和用戶界面。

JavaScript在網站、移動應用、桌面應用和服務器端編程中均有廣泛應用。 1)在網站開發中,JavaScript與HTML、CSS一起操作DOM,實現動態效果,並支持如jQuery、React等框架。 2)通過ReactNative和Ionic,JavaScript用於開發跨平台移動應用。 3)Electron框架使JavaScript能構建桌面應用。 4)Node.js讓JavaScript在服務器端運行,支持高並發請求。

Python更適合數據科學和自動化,JavaScript更適合前端和全棧開發。 1.Python在數據科學和機器學習中表現出色,使用NumPy、Pandas等庫進行數據處理和建模。 2.Python在自動化和腳本編寫方面簡潔高效。 3.JavaScript在前端開發中不可或缺,用於構建動態網頁和單頁面應用。 4.JavaScript通過Node.js在後端開發中發揮作用,支持全棧開發。

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。1)C 用于解析JavaScript源码并生成抽象语法树。2)C 负责生成和执行字节码。3)C 实现JIT编译器,在运行时优化和编译热点代码,显著提高JavaScript的执行效率。

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版
好用的JavaScript開發工具

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!