好久沒寫博客了,都感覺自己快墮落了!今天隨性寫一篇關於異步上傳圖片的程序及插件!
說是程序及插件,其實程序占大頭,所謂的插件只是兩個JS。分別為:jquery.html5upload.js 和 jquery.MultiFile.js
下載地址為:http://files.cnblogs.com/files/chenwolong/upload.rar
其實也沒什么好說的,直接上源代碼吧!
HTML展示如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="LLYY.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script src="usercenter/js/jquery-1.11.1.min.js"></script> <script type="text/javascript" src="usercenter/js/jquery-1.11.1.min.js"></script> <script src="usercenter/js/jquery.html5upload.js" type="text/javascript"></script> <script src="usercenter/js/jquery.MultiFile.js" type="text/javascript"></script> </head> <body> <form id="form1" runat="server"> <div> <input id="mainPicNum" name="mainPicNum" type="file" class="" accept="gif|jpg|jpeg|png|bmp|pic" maxlength="1" onchange="change()" /> </div> <div id="result" style="padding-top:5px;"> </div> </form> </body> </html> <script type="text/javascript"> $(function () { var result = document.getElementById("result"); var input = document.getElementById("mainPicNum"); if (typeof FileReader === 'undefined') { result.innerHTML = "抱歉,你的瀏覽器不支持 FileReader,請使用火狐瀏覽器,或其他兼容瀏覽器!"; input.setAttribute('disabled', 'disabled'); } $("#mainPicNum").MultiFile({ afterFileSelect: function (element, value, master_element) { readFile.call(element); }, afterFileRemove: function (element, value, master_element) { $('img').each(function () { if ($(this).data('src') && (element.files[0].name == $(this).data('src'))) { $(this).remove(); } }); } }); function readFile() { var file = this.files[0]; if (!/image\/\w+/.test(file.type)) { alert("文件必須為圖片!"); return false; } var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function (e) { result.innerHTML += '<img data-src="' + file.name + '" src="' + this.result + '" alt="" style=" height:100px; width:100px;"/>'; } } }); $('#mainPicNum').Html5Upload({ url: 'UploadImage.ashx?action=action', perLoading: function (data, curindex) { // console.log(data) //$(".MultiFile-remove").css("display", "none"); //$(".MultiFile-title").css("display", "none"); }, perLoaded: function (curindex, data) { //alert(data); //alert("上傳頭像成功"); //var img = '<img src="/Images/foo.png" style="background-image: url(\'' + data + '\');" />'; // $('#hiddenImg').val(data); // $(".js_pic").html(img); } }); </script>
一般處理程序如下:

using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Web; namespace LLYY { /// <summary> /// UploadImage 的摘要說明 /// </summary> public class UploadImage : IHttpHandler { public void ProcessRequest(HttpContext context) { if (HttpContext.Current.Request.QueryString["action"] == "action") { uppic(); } context.Response.ContentType = "text/plain"; } protected void uppic() { string fileTim = DateTime.Now.ToString("yyyMddHHmmssffff"); string pic = HttpContext.Current.Request.Form["pic"]; pic = HttpContext.Current.Server.UrlDecode(pic); if (pic != null) { pic = pic.Split(',')[1]; MemoryStream stream = new MemoryStream(Convert.FromBase64String(pic)); Bitmap image = new Bitmap(stream); string fileurl = "/usercenter/uppic/"; string serverPath = HttpContext.Current.Server.MapPath(fileurl); if (Directory.Exists(serverPath) == false)//如果不存在就創建file文件夾 { Directory.CreateDirectory(serverPath); } string picNum=Guid.NewGuid().ToString("N"); string url = fileurl +picNum + ".png"; image.Save(HttpContext.Current.Server.MapPath(url)); HttpContext.Current.Response.Write(url); } HttpContext.Current.Response.End(); } public bool IsReusable { get { return false; } } } }
今天是2018-8-7,我用這段代碼作上傳,發現還是有點小問題的,主要表現在拋出異常:字符數組或字符串長度無效!解決辦法如下:

protected void uppic() { string fileTim = DateTime.Now.ToString("yyyMddHHmmssffff"); string pic = HttpContext.Current.Request.Form["images"]; pic = HttpContext.Current.Server.UrlDecode(pic); if (pic != null) { var imgData = pic.Split(',')[1]; string dummyData = imgData.Trim().Replace("%", "").Replace(",", "").Replace(" ", "+"); if (dummyData.Length % 4 > 0) { dummyData = dummyData.PadRight(dummyData.Length + 4 - dummyData.Length % 4, '='); } byte[] byteArray = Convert.FromBase64String(dummyData); MemoryStream stream = new MemoryStream(byteArray); Bitmap image = new Bitmap(stream); string fileurl = "/usercenter/uppic/"; string serverPath = HttpContext.Current.Server.MapPath(fileurl); if (Directory.Exists(serverPath) == false)//如果不存在就創建file文件夾 { Directory.CreateDirectory(serverPath); } string picNum = Guid.NewGuid().ToString("N"); string url = fileurl + picNum + ".png"; image.Save(HttpContext.Current.Server.MapPath(url)); HttpContext.Current.Response.Write(url); } HttpContext.Current.Response.End(); }
關於產生上述異常的原因,大家可參考:https://www.cnblogs.com/haoliansheng/p/4231846.html
直接復制粘貼即可
但是,我有一個疑問,希望大家能幫我解決。
我的疑問如下:
當網頁第一次加載完成后,我們選擇圖片,執行如下操作:
第一步圖示如下:
這時,圖片已經上傳到了指定路徑。
緊接着,我們進行第二步,
第二步,點擊 x ,把選擇的圖片去掉,然后再重新選擇,圖示如下:
結果后端程序不再執行了,也就是說程序僅僅只會在第一次執行。更改后,不執行,這樣的異步上傳肯定是不能滿足工作需求的,但是,我個人能力有限,實在解決不了,請問各位大神,誰有好辦法解決這個問題!
在此先說聲謝謝!
如果誰能解決,請大度點,把您的優質代碼貼在評論區!萬分感謝!
@陳卧龍的博客