0 ajaxFileUpload簡(jiǎn)介
ajaxFileUpload插件是一個(gè)非常簡(jiǎn)單的基于Jquery的異步上傳文件的插件,使用過(guò)程中發(fā)現(xiàn)很多與這個(gè)同名的,基于原始版本基礎(chǔ)之上修改過(guò)的插件,文件版本比較多,我把我自己使用的ajaxFileUpload文件上傳到博客園上了,想要使用的朋友可以下載:http://xiazai.jb51.net/201611/yuanma/ajaxfileupload(jb51.net).rar。
整個(gè)插件源碼不到200行,實(shí)現(xiàn)非常簡(jiǎn)單,大致原理就是通過(guò)js動(dòng)態(tài)創(chuàng)建隱藏的表單,然后進(jìn)行提交操作,達(dá)到附件上傳的目的,主要實(shí)現(xiàn)在源碼里都有注釋?zhuān)浑y理解,我們也可以基于此簡(jiǎn)單版本實(shí)現(xiàn)更復(fù)雜的操作。
1 ajaxFileUpload使用說(shuō)明
ajaxFileUpload的使用也很簡(jiǎn)單,調(diào)用ajaxFileUpload方法即可,各配置項(xiàng)詳細(xì)說(shuō)明如下:
$.ajaxFileUpload({
type: "post", //請(qǐng)求類(lèi)型:post或get,當(dāng)要使用data提交自定義參數(shù)時(shí)一定要設(shè)置為post
url: "/Shared/Upload", //文件上傳的服務(wù)器端請(qǐng)求地址
secureuri: false, //是否啟用安全提交,一般默認(rèn)為false就行,不用特殊處理
fileElementId: "filePicture", //文件上傳控件的id input type="file" id="filePicture" name="filePicture" accept=".jpg,.jpeg,.png,.bmp" onchange="filePictureChange()" />
dataType: "json", //返回值類(lèi)型,一般設(shè)置為json,還支持html\xml\script類(lèi)型
data: { "id": "1", "name": "test" }, //用于post請(qǐng)求提交自定義參數(shù)
success: function (data, status) { //服務(wù)器成功響應(yīng)處理函數(shù)
},
error: function (data, status, e) { //服務(wù)器響應(yīng)失敗處理函數(shù)
}
});
首先在頁(yè)面添加對(duì)JQuery及ajaxFileUpload的引用,這里的JQuery用的2.1.4版本,經(jīng)測(cè)試用各個(gè)版本基本沒(méi)什么影響。
script src="../../Content/js/jquery-2.1.4.min.js">/script>
script src="../../Content/js/ajaxfileupload.js">/script>
頁(yè)面添加類(lèi)型為file的input標(biāo)簽
復(fù)制代碼 代碼如下:
input type="file" id="filePicture" name="filePicture" accept=".jpg,.jpeg,.png,.bmp" onchange="filePictureChange()" />
通過(guò)accept可以限定打開(kāi)文件選擇對(duì)話(huà)框后,默認(rèn)能選擇的文件類(lèi)型。文件類(lèi)型的定義主要有以下這些
*.3gpp audio/3gpp, video/3gpp 3GPP Audio/Video
*.ac3 audio/ac3 AC3 Audio
*.asf allpication/vnd.ms-asf Advanced Streaming Format
*.au audio/basic AU Audio
*.css text/css Cascading Style Sheets
*.csv text/csv Comma Separated Values
*.doc application/msword MS Word Document
*.dot application/msword MS Word Template
*.dtd application/xml-dtd Document Type Definition
*.dwg image/vnd.dwg AutoCAD Drawing Database
*.dxf image/vnd.dxf AutoCAD Drawing Interchange Format
*.gif image/gif Graphic Interchange Format
*.htm text/html HyperText Markup Language
*.html text/html HyperText Markup Language
*.jp2 image/jp2 JPEG-2000
*.jpe image/jpeg JPEG
*.jpeg image/jpeg JPEG
*.jpg image/jpeg JPEG
*.js text/javascript, application/javascript JavaScript
*.json application/json JavaScript Object Notation
*.mp2 audio/mpeg, video/mpeg MPEG Audio/Video Stream, Layer II
*.mp3 audio/mpeg MPEG Audio Stream, Layer III
*.mp4 audio/mp4, video/mp4 MPEG-4 Audio/Video
*.mpeg video/mpeg MPEG Video Stream, Layer II
*.mpg video/mpeg MPEG Video Stream, Layer II
*.mpp application/vnd.ms-project MS Project Project
*.ogg application/ogg, audio/ogg Ogg Vorbis
*.pdf application/pdf Portable Document Format
*.png image/png Portable Network Graphics
*.pot application/vnd.ms-powerpoint MS PowerPoint Template
*.pps application/vnd.ms-powerpoint MS PowerPoint Slideshow
*.ppt application/vnd.ms-powerpoint MS PowerPoint Presentation
*.rtf application/rtf, text/rtf Rich Text Format
*.svf image/vnd.svf Simple Vector Format
*.tif image/tiff Tagged Image Format File
*.tiff image/tiff Tagged Image Format File
*.txt text/plain Plain Text
*.wdb application/vnd.ms-works MS Works Database
*.wps application/vnd.ms-works Works Text Document
*.xhtml application/xhtml+xml Extensible HyperText Markup Language
*.xlc application/vnd.ms-excel MS Excel Chart
*.xlm application/vnd.ms-excel MS Excel Macro
*.xls application/vnd.ms-excel MS Excel Spreadsheet
*.xlt application/vnd.ms-excel MS Excel Template
*.xlw application/vnd.ms-excel MS Excel Workspace
*.xml text/xml, application/xml Extensible Markup Language
*.zip aplication/zip Compressed Archive
我這里沒(méi)有單獨(dú)放上傳按鈕,添加了onchange事件,在選擇文件后立即上傳文件,onchange時(shí)間定義如下。
function filePictureChange() {
$.ajaxFileUpload({
url: "/Shared/Upload", //用于文件上傳的服務(wù)器端請(qǐng)求地址
type: "post",
secureuri: false, //一般設(shè)置為false
fileElementId: "filePicture", //文件上傳空間的id屬性
dataType: "json", //返回值類(lèi)型 一般設(shè)置為json
success: function (data, status) { //服務(wù)器成功響應(yīng)處理函數(shù)
alert(data.fileName);
alert(data.filePath);
alert(data.fileSize);
},
error: function (data, status, e){ //服務(wù)器響應(yīng)失敗處理函數(shù)
alert(e);
}
});
};
后臺(tái)控制器處理方法如下,使用MD5處理,判斷文件是否已經(jīng)存在,避免文件重復(fù)上傳。
/// summary>
/// 附件上傳
/// /summary>
/// returns>/returns>
public ActionResult Upload()
{
HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
if (files.Count == 0) return Json("Faild", JsonRequestBehavior.AllowGet);
MD5 md5Hasher = new MD5CryptoServiceProvider();
/*計(jì)算指定Stream對(duì)象的哈希值*/
byte[] arrbytHashValue = md5Hasher.ComputeHash(files[0].InputStream);
/*由以連字符分隔的十六進(jìn)制對(duì)構(gòu)成的String,其中每一對(duì)表示value中對(duì)應(yīng)的元素;例如“F-2C-4A”*/
string strHashData = System.BitConverter.ToString(arrbytHashValue).Replace("-", "");
string FileEextension = Path.GetExtension(files[0].FileName);
string uploadDate = DateTime.Now.ToString("yyyyMMdd");
string virtualPath = string.Format("/Data/ComponentAttachments/{0}/{1}{2}", uploadDate, strHashData, FileEextension);
string fullFileName = Server.MapPath(virtualPath);
//創(chuàng)建文件夾,保存文件
string path = Path.GetDirectoryName(fullFileName);
Directory.CreateDirectory(path);
if (!System.IO.File.Exists(fullFileName))
{
files[0].SaveAs(fullFileName);
}
string fileName = files[0].FileName.Substring(files[0].FileName.LastIndexOf("\\") + 1, files[0].FileName.Length - files[0].FileName.LastIndexOf("\\") - 1);
string fileSize = GetFileSize(files[0].ContentLength);
return Json(new { FileName = fileName, FilePath = virtualPath, FileSize = fileSize }, "text/html", JsonRequestBehavior.AllowGet);
}
/// summary>
/// 獲取文件大小
/// /summary>
/// param name="bytes">/param>
/// returns>/returns>
private string GetFileSize(long bytes)
{
long kblength = 1024;
long mbLength = 1024 * 1024;
if (bytes kblength)
return bytes.ToString() + "B";
if (bytes mbLength)
return decimal.Round(decimal.Divide(bytes, kblength), 2).ToString() + "KB";
else
return decimal.Round(decimal.Divide(bytes, mbLength), 2).ToString() + "MB";
}
2 ajaxFileUpload使用過(guò)程中的一些問(wèn)題
2.0 jQuery.handleError is not a function
解決方法:
經(jīng)測(cè)試handlerError只在jquery-1.4.2之前的版本中存在,以后版本中都沒(méi)有這個(gè)函數(shù)了,因此在將handleError這個(gè)函數(shù)復(fù)制到ajaxFileUpload.js中,就行了
uploadHttpData: function (r, type) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if (type == "script")
jQuery.globalEval(data);
// Get the JavaScript object, if JSON is used.
if (type == "json")
eval("data = " + data);
//eval("data = \"" + data + "\"");
// evaluate scripts within html
if (type == "html")
jQuery("div>").html(data).evalScripts();
return data;
},
handleError: function (s, xhr, status, e) {
// If a local callback was specified, fire it
if (s.error) {
s.error.call(s.context || s, xhr, status, e);
}
// Fire the global callback
if (s.global) {
(s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]);
}
}
更多精彩內(nèi)容,請(qǐng)點(diǎn)擊《jQuery上傳操作匯總》,進(jìn)行深入學(xué)習(xí)和研究。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- jquery ajaxfileuplod 上傳文件 essyui laoding 效果【防止重復(fù)上傳文件】
- jquery-file-upload 文件上傳帶進(jìn)度條效果
- jQuery插件ajaxFileUpload使用詳解
- jQuery File Upload文件上傳插件使用詳解
- jQuery插件ajaxFileUpload異步上傳文件
- jQuery獲取file控件中圖片的寬高與大小
- 從重置input file標(biāo)簽中看jQuery的 .val() 和 .attr(“value”) 區(qū)別
- jQuery插件ajaxfileupload.js實(shí)現(xiàn)上傳文件
- JQuery fileupload插件實(shí)現(xiàn)文件上傳功能
- jquery獲取file表單選擇文件的路徑、名字、大小、類(lèi)型