1

我有這片如下面的代碼在我的MVC控制器上傳IMG並將其保存在文件夾中:MVC,Angularjs,HttpPostedFileBase.SaveAs是刷新頁面?

public ActionResult UploadLogo(HttpPostedFileBase file) 
    { 


     var path = ""; 
     if (file != null) 
     { 

      if (file.ContentLength > 0) 
      { 
       if (Path.GetExtension(file.FileName).ToLower() == ".jpg" || 
        Path.GetExtension(file.FileName).ToLower() == ".png" || 
        Path.GetExtension(file.FileName).ToLower() == ".gif" || 
        Path.GetExtension(file.FileName).ToLower() == ".jpeg") 
       { 

        path = Server.MapPath("~/GroupApp/Content/Images/"); 

        if (!Directory.Exists(path)) 
        { 
         Directory.CreateDirectory(path); 
        } 
        path = Path.Combine(path, file.FileName); 

        file.SaveAs(path); 

        return new HttpStatusCodeResult(HttpStatusCode.OK); 
       } 
      } 
     } 
     return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, ""); // :(
    } 

答:這是我在angularjs服務代碼:

groupApp.factory('uploadLogo', ['$http', '$q', '$timeout', function ($http, $q, $timeout) { 


var _uploadLogo = function (file) { 

    var deferred = $q.defer(); 
    var controllerQuery = "groupApi/uploadLogo"; 

    $timeout(function() { 
     deferred.notify(true); 
    }, 0) 


    var _file = new FormData(); 


    _file.append('file', file, file.name); 

    $http.post(controllerQuery, _file, { 
     transformRequest: angular.identity, 
     headers: { 'Content-Type': undefined }, 
     enctype: 'multipart/form-data' 

    }) 
     .then(function (result) { 


      $timeout(function() { 
       deferred.resolve(result); 
      }, 200); 

     }, 
      function (error) { 

       deferred.reject(error); 
      }); 
    return deferred.promise; 

}; 


return { 
    uploadLogo: _uploadLogo, 
} 

}]); 

而且什麼都可以我說,它很好用,但爲什麼在執行這個代碼之後,整個視圖更新?

我沒有任何刷新或角度控制器中的視圖更改功能。

當我正在調試代碼,並且命中行符:'file.SaveAs(path)'時,我注意到在那個頁面開始重新加載之後。

任何人都可以向我解釋爲什麼?之後如何防止重新加載頁面?

回答

0
Can you remove the timeout function and access the result directly. 
Like this 

$http.post(controllerQuery, _file, { 
     transformRequest: angular.identity, 
     headers: { 'Content-Type': undefined }, 
     enctype: 'multipart/form-data' 

    }) 
     .then(function (result) { 
       deferred.resolve(result); 
     }, 
      function (error) { 

       deferred.reject(error); 
      }); 
    return deferred.promise; 

}; 
+0

當然,我使用$超時僅用於測試(加載COG)。 – Piosek