【问题标题】:Create file on client side and send to server在客户端创建文件并发送到服务器
【发布时间】:2017-05-11 22:13:48
【问题描述】:

我想使用 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() 但也不起作用。 cat 如何获取选项 JSON 对象并将其像文件一样传递给服务器?

【问题讨论】:

    标签: angularjs file model-view-controller


    【解决方案1】:
        //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。

    让我知道这是否有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-25
      • 2015-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-22
      相关资源
      最近更新 更多