2014-02-08 50 views
0
   Hi All, 

我的環境:角1.2.10 - 清風 - 淨 - 實體框架ADO的.Net 6.0角1.2.10 - 清風 - .NET 4.5 - 與格式文件上傳

我見過很多文件上傳(單獨),如https://github.com/danialfarid/angular-file-upload 我試圖上傳一個文件,但沒有成功。

你有什麼想法嗎?

我做對角端MVVM,它提供了:

角 - HTML:

<section id="register-view" class="mainbar" data-ng-controller="register as vm"> 
    <form name="RegisterForm" ng-submit="submit()" data-n ng-controller="vm.Ctrl"> 
     <section class="matter"> 
      <div class="container"> 
       <div class="row"> 
        <div class="col-md-12"> 
         <ul class="today-datas"> 
          <li class="blightblue"> 
           <div class="pull-left"><i class="fa fa-plane"></i></div> 
           <div class="datas-text pull-right"> 
            <span class="bold">11, 12, 13 Février 2014<br />Microsoft Techdays, France</span> 
           </div> 
           <div class="clearfix"></div> 
          </li> 
         </ul> 
        </div> 
       </div> 
       <div class="row"> 
        <div class="col-md-6"> 
         <div class="widget wviolet"> 
          <div data-cc-widget-header title="{{vm.title}}" 
           allow-collapse="true"></div> 
          <div class="widget-content text-center text-info"> 
           <table class="table table-condensed table-striped"> 
            <tbody> 
             <tr> 
              <td>Nom utilisateur</td> 
              <td><input ng-model="vm.user.UserName" required /></td> 
              <td></td> 
             </tr> 
             <tr> 
              <td>Mot de passe</td> 
              <td><input ng-model="vm.user.Membership.Password" required type="password" /></td> 
              <td></td> 
             </tr> 
             <tr> 
              <td>Confirmation mot de passe</td> 
              <td><input ng-model="vm.user.Membership.ConfirmPassword" required type="password" /></td> 
              <td></td> 
             </tr> 
             <tr> 
              <td>Photo <strong>(facultatif)</strong></td> 
              <td> 
               <!--<input ng-model="vm.user.Photo" type="file" />--> 
               <div ng-controller="vm.CtrlPhoto"> 
                <input type="file" id="fileToUpload" ng-file-select="onFileSelect($files)" /> 
               </div> 
               <!--<div id="dropbox" class="dropbox" ng-class="dropClass"><span>Drop files here...</span></div>--> 
              </td> 
              <td></td> 
             </tr> 
             <tr> 
              <td>Prénom</td> 
              <td><input ng-model="vm.user.FirstName" required /></td> 
              <td></td> 
             </tr> 
             <tr> 
              <td>Nom</td> 
              <td><input ng-model="vm.user.LastName" required /></td> 
              <td></td> 
             </tr> 
             <tr> 
              <td>Email</td> 
              <td><input ng-model="vm.user.Membership.Email" required type="email" /></td> 
              <td></td> 
             </tr> 
             <tr> 
              <td>Téléphone <strong>(facultatif)</strong></td> 
              <td><input ng-model="vm.user.Phone" type="tel" /></td> 
              <td></td> 
             </tr> 
             <tr> 
              <td>Date de naissance <strong>(facultatif)</strong></td> 
              <td> 
               <!--<input ng-model="vm.user.Phone" type="tel" />--> 
               <select> 
                <option value="0"></option> 
                <option value="1">1</option> 
                <option value="2">2</option> 
                <option value="3">3</option> 
                <option value="4">4</option> 
                <option value="5">5</option> 
                <option value="6">6</option> 
                <option value="7">7</option> 
                <option value="8">8</option> 
                <option value="9">9</option> 
                <option value="10">10</option> 
                <option value="11">11</option> 
                <option value="12">12</option> 
                <option value="13">13</option> 
                <option value="14">14</option> 
                <option value="15">15</option> 
                <option value="16">16</option> 
                <option value="17">17</option> 
                <option value="18">18</option> 
                <option value="19">19</option> 
                <option value="20">20</option> 
                <option value="21">21</option> 
                <option value="22">22</option> 
                <option value="23">23</option> 
                <option value="24">24</option> 
                <option value="25">25</option> 
                <option value="26">26</option> 
                <option value="27">27</option> 
                <option value="28">28</option> 
                <option value="29">29</option> 
               </select> 
               <select> 
                <option value="1">Janvier</option> 
                <option value="2">Février</option> 
                <option value="3">Mars</option> 
                <option value="4">Avril</option> 
                <option value="5">Mai</option> 
                <option value="6">Juin</option> 
                <option value="7">Juillet</option> 
                <option value="8">Août</option> 
                <option value="9">Septembre</option> 
                <option value="10">Octobre</option> 
                <option value="11">Novembre</option> 
                <option value="12">Décembre</option> 
               </select> 
              </td> 
              <td></td> 
             </tr> 
             <tr> 
              <td>Position</td> 
              <td><textarea ng-model="vm.user.Position" wrap="hard" rows="5" cols="60" /></td> 
              <td></td> 
             </tr> 
             <tr> 
              <td>Intérêts</td> 
              <td><textarea ng-model="vm.user.Interests" rows="5" cols="60" /></td> 
              <td><input type="submit" id="submit" value="Submit" /></td> 
             </tr> 
            </tbody> 
           </table> 
          </div> 
          <div class="widget-foot"> 
           <div class="clearfix"></div> 
          </div> 
         </div> 
        </div> 
        <div class="col-md-6" /> 
       </div> 
      </div> 
     </section> 
    </form> 
</section> 

JS的視圖模型:

(function() { 
    'use strict'; 
    var controllerId = 'register'; 
    angular.module('app').controller(controllerId, ['common', 'datacontext', 'entityManagerFactory', register]); 

    function register(common, datacontext, entityManagerFactory) { 
     var getLogFn = common.logger.getLogFn; 
     var log = getLogFn(controllerId); 

     var vm = this; 
     vm.title = 'Register'; 
     vm.Ctrl = Ctrl; 
     vm.CtrlPhoto = CtrlPhoto; 

     var user = { 
      ApplicationId: "1", 
      UserId: "", 
      UserName: "", 
      LoweredUserName: "", 
      MobileAlias: "", 
      IsAnonymous: false, 
      LastActivityDate: "", 
      FirstName: "", 
      LastName: "", 
      BirthDate: "", 
      CountryCode: "", 
      Phone: "", 
      Photo: "", 
      PathPhoto: "", 
      Position: "", 
      Interests: "", 
      Application: "", 
      Membership: { 
       ApplicationId: "1", 
       UserId: "", 
       Password: "", 
       PasswordFormat: "", 
       PasswordSalt: "", 
       MobilePIN: "", 
       Email: "", 
       LoweredEmail: "", 
       PasswordQuestion: "", 
       PasswordAnswer: "", 
       IsApproved: "", 
       IsLockedOut: "", 
       CreateDate: "", 
       LastLoginDate: "", 
       LastPasswordChangedDate: "", 
       LastLockoutDate: "", 
       FailedPasswordAttemptCount: "", 
       FailedPasswordAttemptWindowStart: "", 
       FailedPasswordAnswerAttemptCount: "", 
       FailedPasswordAnswerAttemptWindowStart: "", 
       Comment: "", 
       Application: "", 
       User: "" 
      }, 
      Missions: "", 
      PersonalizationPerUsers: "", 
      Profile: "", 
      WebpagesOAuthMemberships: "", 
      Roles: "", 
      PostedFile: "" 
     }; 
     vm.user = user; 

     activate(); 

     function activate() { 
      common.activateController(null, controllerId) 
       .then(function() { 
        log('Activated Register View'); 
       }); 
     } 

     function CtrlPhoto($scope) { 
      $scope.onFileSelect = function ($files) { 
       //$files: an array of files selected, each file has name, size, and type. 
       for (var i = 0; i < $files.length; i++) { 
        var file = $files[i]; 
        vm.user.PostedFile = file; 
        //$scope.upload = $upload.upload({ 
        // url: '/IdPhoto', //upload.php script, node.js route, or servlet url 
        // // method: POST or PUT, 
        // // headers: {'headerKey': 'headerValue'}, 
        // // withCredential: true, 
        // data: vm.myModelObj, 
        // file: file, 
        // // file: $files, //upload multiple files, this feature only works in HTML5 FromData browsers 
        // /* set file formData name for 'Content-Desposition' header. Default: 'file' */ 
        // //fileFormDataName: myFile, //OR for HTML5 multiple upload only a list: ['name1', 'name2', ...] 
        // /* customize how data is added to formData. See #40#issuecomment-28612000 for example */ 
        // //formDataAppender: function(formData, key, val){} //#40#issuecomment-28612000 
        //}).progress(function (evt) { 
        // console.log('percent: ' + parseInt(100.0 * evt.loaded/evt.total)); 
        //}).success(function (data, status, headers, config) { 
        // // file is uploaded successfully 
        // console.log(data); 
        //}); 
        //.error(...) 
        //.then(success, error, progress); 
       } 
      } 
     } 

     function Ctrl($scope) { 
      $scope.submit = function() { 
       //vm.user.Photo = document.getElementById("fileToUpload"); 
       datacontext.Register(vm.user) 
          //.then(loadFile($upload)) 
          .then(common.logger.log("File posted")) 
          .catch(failCallback) 

       //$upload.upload({ 
       // url: '~/IdPhoto', 
       // file: vm.user.PathPhoto // for single file 
       //}) 
       //.then(function (data) { 
       // vm.user.PathPhoto.fileId = data; 
       //}) 
      }; 
      function loadFile($upload) { 
       //var fd = new FormData(); 
       var fileToUpload = document.getElementById("fileToUpload"); 
       //fd.append("uploadedFile", fileToUpload); 

       //var xhr = new XMLHttpRequest(); 

       //xhr.open("POST", '/IdPhoto'); 
       //xhr.send(fd) 



       $upload.upload({ 
        url: '/IdPhoto', 
        file: fileToUpload, 
       }).then(function (data, status, headers, config) { 
        // file is uploaded successfully 
        //console.log(data); 
       }).catch(failCallback(error)); 

      } 
     } 

     function failCallback(error) { 
      var msg = 'Error Posting File ' + error.message; 
      common.logger.logError(msg, error); 
      throw error; 
     } 

    } 
})(); 

由ApiController - BreezeController側post方法給出:

[System.Web.Http.AcceptVerbs("POST")] 
//[HttpPost] 
public string Register(User user) 
{ 
    System.Web.Security.MembershipCreateStatus status = MembershipCreateStatus.UserRejected; 
    //pour les nouvelles inscriptions il n'y a pas de nwpassword et de confirmnewpassword 
    //ModelState.Remove("user.Membership.NewPassword"); 
    //ModelState.Remove("user.Membership.ConfirmNewPassword"); 

    //if (ModelState.IsValid) 
    //{ 
     // Tentative d'inscription de l'utilisateur 
     try 
     { 
      CVAppMembershipProvider provider = (CVAppMembershipProvider)System.Web.Security.Membership.Providers["CVAppMembershipProvider"]; 
      var httpContext = (HttpContextWrapper)Request.Properties["MS_HttpContext"]; 
      var foo = httpContext.Request.Form["Foo"]; 


      MembershipUser usr = provider.CreateUser(user, out status); 

      if (status == MembershipCreateStatus.Success) 
      { 
       FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, 
        usr.UserName, 
        DateTime.Now, 
        DateTime.Now.AddMonths(1), 
        false, 
        "", //userData 
        FormsAuthentication.FormsCookiePath); 

       ////Encrypt the ticket. 
       string encTicket = FormsAuthentication.Encrypt(ticket); 

       var resp = new HttpResponseMessage(); 
       //create and set cookie in response 
       var cookie = new CookieHeaderValue(FormsAuthentication.FormsCookieName, encTicket); 
       cookie.Expires = DateTimeOffset.Now.AddMonths(1); 
       cookie.Domain = Request.RequestUri.Host; 
       cookie.Path = "/"; 
       resp.Headers.AddCookies(new CookieHeaderValue[] { cookie }); 
      } 
      else 
      { 
       ModelState.AddModelError(status.ToString(), GetErrorMessage(status)); 
      } 
     } 
     catch (Exception e) 
     { 
      ModelState.AddModelError("", e.Message); 
     } 
    //} 

    return status.ToString(); 

} 

在這個post方法中,我想對viewModel花費的用戶(JSon格式)進行一些處理,這是可以的。 在同一時間,我想從窗體上(從角形式元素'fileToUpload')上傳文件。可能嗎 ?

在互聯網上找到的所有例子都沒有給出答案。

我想用於序列化的Json格式無法使用該文件。

XML序列化會有幫助嗎?

任何更簡單的解決方案?

Thanx提前對您有所幫助

+0

這不是一個微風問題,因爲Breeze沒有涉及任何相關的方式。這就是我刪除Breeze標籤的原因。 – Ward

回答

0

我找到了解決我的問題。 它由只做了UploadFile,要花費用戶的UploadFile(更改名稱==>註冊),它給出了的datacontext(JavaScript的):

function Register($upload, user, postedFile) { 
    return $q.when(
        $upload.upload({ 
         url: 'CVApp/User/Register', //upload.php script, node.js route, or servlet url 
         method: 'POST', 
         // headers: {'headerKey': 'headerValue'}, 
         // withCredential: true, 
         data: user, 
         file: postedFile, 
         // file: $files, //upload multiple files, this feature only works in HTML5 FromData browsers 
         /* set file formData name for 'Content-Desposition' header. Default: 'file' */ 
         //fileFormDataName: myFile, //OR for HTML5 multiple upload only a list: ['name1', 'name2', ...] 
         /* customize how data is added to formData. See #40#issuecomment-28612000 for example */ 
         //formDataAppender: function(formData, key, val){} //#40#issuecomment-28612000 
        } 
       ) 
       .then(successCallback) 
       .catch(failCallback)     // same as 'then(null, failCallback)' 
       .finally(finalCallback) // sort of like 'then(finalCallback, finalCallback)' 
    ); 
} 

在服務器端,它給在ApiController中:

[System.Web.Http.AcceptVerbs("POST")] 
public async Task<HttpResponseMessage> Register() 
{ 
    // Check if the request contains multipart/form-data. 
    if (!Request.Content.IsMimeMultipartContent()) 
    { 
     throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
    } 

    string root = HttpContext.Current.Server.MapPath("~/IdPhoto"); 
    var provider = new MultipartFormDataStreamProvider(root); 

    try 
    { 
     // Read the form data. 
     await Request.Content.ReadAsMultipartAsync(provider); 

     User user = new User(provider.FormData); 

     System.Web.Security.MembershipCreateStatus status = MembershipCreateStatus.UserRejected; 
     CVAppMembershipProvider mProvider = (CVAppMembershipProvider)System.Web.Security.Membership.Providers["CVAppMembershipProvider"]; 

     MembershipUser usr = mProvider.CreateUser(user, out status); 

     if (status == MembershipCreateStatus.Success) 
     { 
      FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, 
       usr.UserName, 
       DateTime.Now, 
       DateTime.Now.AddMonths(1), 
       false, 
       "", //userData 
       FormsAuthentication.FormsCookiePath); 

      ////Encrypt the ticket. 
      string encTicket = FormsAuthentication.Encrypt(ticket); 

      var resp = new HttpResponseMessage(); 
      //create and set cookie in response 
      var cookie = new CookieHeaderValue(FormsAuthentication.FormsCookieName, encTicket); 
      cookie.Expires = DateTimeOffset.Now.AddMonths(1); 
      cookie.Domain = Request.RequestUri.Host; 
      cookie.Path = "/"; 
      resp.Headers.AddCookies(new CookieHeaderValue[] { cookie }); 
     } 
     else 
     { 
      throw new Exception(status.ToString() + " - " + GetErrorMessage(status)); 
     } 

     // This illustrates how to get the file names. 
     foreach (MultipartFileData file in provider.FileData) 
     { 
      string fileName = file.Headers.ContentDisposition.FileName; 
      if (fileName.StartsWith("\"") && fileName.EndsWith("\"")) 
      { 
       fileName = fileName.Trim('"'); 
      } 
      if (fileName.Contains(@"/") || fileName.Contains(@"\")) 
      { 
       fileName = Path.GetFileName(fileName); 
      } 

      fileName = user.UserName.Replace(" ", "_") + "." + fileName.Substring(fileName.IndexOf(".") + 1); 

      File.Copy(file.LocalFileName, Path.Combine(root, fileName)); 
     } 
     return Request.CreateResponse(HttpStatusCode.OK); 
    } 
    catch (Exception e) 
    { 
     //return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); 
     throw e; 
    } 
} 

etvoilà!有用。

現在我只需要在處理時擁有「BusyIndi​​cator」,在最後有錯誤/正確的消息,並且能夠按我想要的順序執行我的異步方法(如果可能的話,我認爲那麼「那麼」可以做到這一點),我仍在尋找,我想我會在互聯網上快速找到它。

Thanx