我对编码完全陌生,所以如果这个问题很愚蠢,请原谅我。我正在尝试在 html 页面上添加文件上传按钮,以便用户将文件上传到服务器。该项目使用 html、angularjs 和 api 使用 c#。
我的HTML代码如下:
<div ng-controller="MyCtrl">
<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>
</div>
我在 Controller 中的 Angularjs 函数是:
$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append('file', files[0]);
$http({
method: 'POST',
url: '/Users/x/Documents/api/FileController.cs',
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success(function(){alert('Success')}).error(function(){alert('Error')});
};
在 asp.net 的 FileController.cs 文件中,我有一个函数:
[HttpPost]
public ActionResult Index(HttpPostedFileBase file) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path + FileName);
}
return RedirectToAction("Index");
}
http 帖子一直显示错误。
我的问题是:
- 该网址的格式正确吗? url: '/Users/x/Documents/api/FileController.cs'
- http 可以发布到 .cs 文件吗?
- c#写的函数的功能是不是少了点什么?
- 在 C# 中是否需要加载页面才能接收帖子?
最佳答案
您不能通过邮寄访问 cs 文件,而是通过方法访问。所以 url 应该以/File:
结尾/Users/x/Documents/api/File
首先尝试使用可以通过浏览器直接访问的 get 方法进行测试。如果有效,请继续您的帖子
关于javascript - Angularjs http post 到 c# 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30070702/