MVC4.0非同步負載檔案,mvc4.0非同步載入

來源:互聯網
上載者:User

MVC4.0非同步負載檔案,mvc4.0非同步載入


非同步上傳頭像

前台:

 <form id="FileForm">
                        <span style="width: 100px;">
                            <img id="oldimghead" src="~/Content/images/HeadPortraitMan.jpg" style="width: 100px; height: 100px;" />
                            <img id="imghead" src="" style="display: none; width: 100px; height: 100px;" />
                        </span>
                        <span id="uploadImg" style="margin-left: 10px; width: 100px; height: 100px;">
                            <input type="file" name="file" onchange="previewImage()" id="file" value="上傳資料" /><img src="~/Content/images/ModifyHead.jpg" />
                        </span>
                    </form>


js:
  function previewImage() {
        $("#oldimghead").hide();
        $("#imghead").show();
        $("#FileForm").ajaxSubmit({
            success: function (url) {
                ImageUrl = "/FileServer/UserPhoto" + url;
                if (url != "" && url != null) {
                    $("#imghead").attr("src", ImageUrl);
                }
                else
                    $("#imghead").attr("src", "~/Content/images/HeadPortraitMan.jpg");
            },
            error: function (error) { alert(error); },
            url: '/Member/UploadPhoto', /*設定post提交到的頁面*/
            type: "post", /*設定表單以post方法提交*/
            dataType: "json" /*設定返回值類型為文本*/
        });
    }

後台:
  //上傳頭像
        public ActionResult UploadPhoto()
        {
            // var LoginModel = Session["UserLogin"] != null ? Session["UserLogin"] as LoginModel : null;
            // int CusACCPInfoID = LoginModel.CusACCPInfo_ID;//客戶連絡人ID
            int CusACCPInfoID = 20;
            HttpPostedFileBase hp = Request.Files["file"];
            string uploadPath = Server.MapPath("/FileServer/UserPhoto");
            var msg = UploadHelper.UploadImage(CusACCPInfoID, 1, hp, uploadPath);
            return Json(msg, JsonRequestBehavior.AllowGet);
        }
伺服器儲存:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace WMJQ.Common
{
   public static class UploadHelper
    {
       /// <summary>
       /// 圖片上傳
       /// </summary>
       /// <param name="CustomID">客戶個性ID</param>
       /// <param name="CConactID">客戶連絡人個性ID</param>
       /// <param name="hp">圖片資源</param>
       /// <param name="uploadPath">Base路徑</param>
       /// <returns></returns>
       public static string UploadImage(int CustomID, int CConactID, HttpPostedFileBase hp, string uploadPath)
       {
           //定義錯誤訊息
           string msg = "";
       
           if (hp == null)
           {
               msg = "請選擇檔案.";
           }        
           //擷取檔案名稱
           string fileName = DateTime.Now.ToString("yyyyMMddHHmmssms") + System.IO.Path.GetExtension(hp.FileName); ;
           //擷取檔案大小
           long contentLength = hp.ContentLength;
           //檔案不能大於1M
           if (contentLength > 1024 * 1024 * 2)
           {
               msg = "檔案大小超過限制要求.";
           }
           if (!checkFileExtension(hp.FileName))
           {
               msg = "檔案為不可上傳的類型.";
           }
           //儲存檔案的實體路徑
           string saveFilePath = "/" + CustomID + "/" + CConactID ;
           string saveFile = uploadPath + saveFilePath + "/" + fileName;
           Directory.CreateDirectory(uploadPath + saveFilePath);
           try
           {
               //儲存檔案
               hp.SaveAs(saveFile);
               msg = saveFilePath + "/" + fileName;
           }
           catch
           {
               msg = "上傳失敗.";
           }
           return msg;

       }


       /// <summary>
       /// 檢查檔案尾碼名是否符合要求
       /// </summary>
       /// <param name="fileName"></param>
       /// <returns></returns>
       private static bool  checkFileExtension(string fileName)
       {
           //擷取檔案尾碼
           string fileExtension = System.IO.Path.GetExtension(fileName);
           if (fileExtension != null)
               fileExtension = fileExtension.ToLower();
           else
               return false;

           if (fileExtension != ".jpeg" && fileExtension != ".gif" && fileExtension != ".png" && fileExtension != ".jpg")
               return false;

           return true;
       }
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.