如何将文件从AngularJS $ http服务上传到asp.net MVC

问题描述:

我试图从服务上传文件到控制器。我检查,该文件是在服务上,但我不能把它传递给控制器​​

uploadFile = function (file) { 

    var promise = $http(
    { 
     method: 'POST', 
     withCredentials: true, 
     url: self.baseUrl + 'Admin/uploadFile', 
     contentType: 'undefined', 
     data: { 
      file: file 
     } 

    }); 
    return promise; 
} 

[HttpPost] 
public ActionResult uploadFile() 
{ 
    try 
    { 
     var file = Request.Files[0]; 
     Response.StatusCode = 200; 
     return Content("updated"); 
    } 
    catch (Exception ex) 
    { 
     Response.StatusCode = 500; 
     return Content("Fail"); 
    } 
} 
+0

所以,你的问题实际上是“如何从angularjs前端上传文件[您使用的后端式技术]”,对不对?提及您使用的标签中的后端技术会很有帮助。 –

+0

这是asp.net MVC ...你可以从代码中知道。我想你可能需要使用headers对象来为你的$ http请求设置标题(例如 - '''headers:{'Content-Type':undefined}'''而不是你拥有它的方式 – bri

+0

谢谢。当我插入:标题:{'Content-Type':undefined}我得到404错误 – user6934713

正确的头名是'Content-Type'1并应设置为primitive valueundefined2,不是字符串'undefined'

uploadFile = function (file) { 

    var promise = $http(
    { 
     method: 'POST', 
     withCredentials: true, 
     url: self.baseUrl + 'Admin/uploadFile', 
     //ERRONEOUS 
     //contentType: 'undefined', 

     //USE 
     headers: { 'Content-Type': undefined }, 

     data: { 
      file: file 
     } 

    }); 
    return promise; 
} 

通常,AngularJS将内容类型设置为application/json。通过将内容类型设置为undefined,可以通过XHR API send method将内容类型设置为适当的值。

欲了解更多信息,请参阅AngularJS $http Service API Reference - Setting HTTP Headers