標籤:led sage 上傳檔案 pat his script response style change
1、說明
ajaxfileupload.js是一款jQuery外掛程式,用於通過ajax上傳檔案。
:http://files.cnblogs.com/files/lengzhan/ajaxfileupload.zip
2、使用方法
首先引用js指令碼
<script src="Scripts/jquery/jquery-1.9.1.js" type="text/javascript"></script> <script src="Scripts/ajaxfileupload.js" type="text/javascript"></script>
<script type="text/javascript"> $(function () { $("#btnUpload").on(‘click‘, DoUpload); }) function DoUpload() { var image = $("#txtPath").val(); if ($.trim(image) == "") { alert("請選擇檔案!"); return; } $.ajaxFileUpload( { url: ‘Handler/FileUploadHandler.ashx?type=Attachment‘, secureuri: false, fileElementId: $("#fleFile").attr("id"), dataType: ‘json‘, success: function (data, status) { if (data.url === "") { alert("上傳失敗!"); } else { alert("上傳成功!"); } }, error: function (result) { alert("上傳失敗!"); } }); } </script>
然後是html代碼
<div id="ImageMaintain"> <input type="hidden" name="hidImgUrl" id="hidImgUrl" value="" /> <div id="uploadarea"> <input id="txtPath" type="text" disabled="disabled" /> <input id="fleFile" type="file" name="fleFile" onchange="document.getElementById(‘txtPath‘).value = this.value;return false;" /> <input id="btnSelect" type="button" value="選擇" class="button" style="width: 60px;" /> <input id="btnUpload" type="button" value="上傳" class="button" style="width: 60px;" /> </div> </div>
最後是一般處理常式
<%@ WebHandler Language="C#" Class="FileUploadHandler" %>using System;using System.Web;using System.IO;public class FileUploadHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string strMessage = string.Empty; string strUrl = string.Empty; string strFloderName = "Upload"; string strNewFilePath = string.Empty; string strFileName = Path.GetFileName(context.Request.Files[0].FileName); string strOldFileName = Path.GetFileName(context.Request.Files[0].FileName); int intFileSize = context.Request.Files[0].ContentLength; string data = ""; if (context.Request.Files.Count > 0 && strFileName != "") { string strExt = Path.GetExtension(context.Request.Files[0].FileName); strExt = strExt.TrimStart(‘.‘).ToLower(); strFloderName = strFloderName + "/" + "File/" + DateTime.Now.ToString("yyyyMMdd"); string path = HttpContext.Current.Server.MapPath("../" + strFloderName); try { strFileName = Guid.NewGuid().ToString() + ("." + strExt); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } strNewFilePath = Path.Combine(path, strFileName); context.Request.Files[0].SaveAs(strNewFilePath); } catch (Exception ex) { strMessage = "儲存失敗"; strUrl = string.Empty; } } strMessage = ""; strUrl = strFloderName + "/" + strFileName; data = "{\"strUrl\":\"" + strUrl + "\",\"strMessage\":\"" + strMessage + "\"}"; context.Response.Write(data); context.Response.End(); } public bool IsReusable { get { return false; } }}
3、圖片上傳
這裡會把DEMO上傳至部落格園,:http://files.cnblogs.com/files/lengzhan/UploadAjaxFile.zip
Jquery+ajaxfileupload上傳檔案