2017-05-11 88 views
0

我想使用Angular或Javascript在客戶端創建一個文件並將其發送到服務器。 使用MVC控制器我的服務器功能在客戶端創建文件併發送到服務器

public void SavePivotFile(HttpPostedFileBase file) 
    { 
     try 
     { 
      if (file.ContentLength > 0) 
      { 
       var fileName = Path.GetFileName(file.FileName); 
       var path = Path.Combine(Server.MapPath("~"), System.Configuration.ConfigurationManager.AppSettings["reportsFolder"].ToString(), fileName); 
       file.SaveAs(path); 
      } 
     } 
     catch(Exception e) 
     { 
      throw; 
     } 
    } 

現在,在我的客戶端,我有我想在SavePivotFile發送像文件的對象。我試過這個,但沒有奏效。對象的'選項'是JSON。

  $http({ 
       method: 'GET', 
       url: '/FileManager/SavePivotFile', 
       params: { 
        file: options, 
       } 
      }).then(function successCallback(response) { 
       showNotification('The changes have been saved.', 'info'); 
      }, function errorCallback(response) { 
       showNotification('Failed to save the file.', 'error'); 
      }); 

此外,我試圖在發送之前創建新的FormData(),但也不起作用。如何貓選擇JSON對象並將其傳遞給服務器像文件?

回答

0
//C# Code 
    [HttpPost] 
    [Route('FileManager/SavePivotFile')] 
    // you can use [Allow(Role)] to allow particular role. Google it! 
    public void SavePivotFile(HttpPostedFileBase file) 
{ 
    try 
    { 
     if (file.ContentLength > 0) 
     { 
      var fileName = Path.GetFileName(file.FileName); 
      var path = Path.Combine(Server.MapPath("~"), System.Configuration.ConfigurationManager.AppSettings["reportsFolder"].ToString(), fileName); 
      file.SaveAs(path); 
     } 
    } 
    catch(Exception e) 
    { 
     throw; 
    } 
} 



//Angular Code 
$http.post('FileManager/SavePivotFile',options)//Optionsistheobjectuwanttosend 
     .success(function(res){ 
     //your code. since the c# method isvoid you will not get any response 
     }) 
     .error(function(e){ 
     //your error handling 
     }) 

HttpPostedFileBase模型應該類似於選項。這樣你就可以在c#中訪問JSON。

讓我知道這是否工作。

相關問題