轉至:http://www.cnblogs.com/fonour/p/ajaxFileUpload.html 0、下載 http://files.cnblogs.com/files/fonour/ajaxfileupload.js 1、引用ajaxfileupload.js 2、頁面添加類型為fil ...
轉至:http://www.cnblogs.com/fonour/p/ajaxFileUpload.html
0、下載 http://files.cnblogs.com/files/fonour/ajaxfileupload.js
1、引用ajaxfileupload.js
<script src="../../Content/js/jquery-2.1.4.min.js"></script> <script src="../../Content/js/ajaxfileupload.js"></script>
2、頁面添加類型為file的input標簽
<input type="file" id="filePicture" name="filePicture" accept=".jpg,.jpeg,.png,.bmp" onchange="filePictureChange()" />
3、添加了onchange事件,在選擇文件後立即上傳文件,onchange時間定義如下
var filePictureChange = function(){ $.ajaxFileUpload({ type: "post", //請求類型:post或get,當要使用data提交自定義參數時一定要設置為post url: "/Shared/Upload", //文件上傳的伺服器端請求地址 secureuri: false, //是否啟用安全提交,一般預設為false就行,不用特殊處理 fileElementId: "filePicture", //文件上傳控制項的id <input type="file" id="filePicture" name="filePicture" accept=".jpg,.jpeg,.png,.bmp" onchange="filePictureChange()" /> dataType: "json", //返回值類型,一般設置為json,還支持html\xml\script類型 data: { "id": "1", "name": "test" }, //用於post請求提交自定義參數 success: function (data, status) { //伺服器成功響應處理函數 }, error: function (data, status, e) { //伺服器響應失敗處理函數 } }); }
4、後臺控制器方法
/// <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(); /*計算指定Stream對象的哈希值*/ byte[] arrbytHashValue = md5Hasher.ComputeHash(files[0].InputStream); /*由以連字元分隔的十六進位對構成的String,其中每一對錶示value中對應的元素;例如“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); //創建文件夾,保存文件 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"; }