asp.net mvc 上傳文件


轉至: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>
        [HttpPost]
        public ActionResult AjaxUpload()
        {
            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("/upload/{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";
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM