我提到了一些Stack overflow问题,我尝试了以下代码。以下代码未访问Web API。 我尝试使用普通文本,然后点击但不是文件。最后我总结了Web API路径和方法都很好,唯一的问题是File。请帮助我如何使用AngularJS将文件上传到.NET Web API。
我的HTML代码
<input id="file_input_file" ng-files="getTheFiles($files)" type="file" accept=".csv" />
<input type="button" data-ng-click="ImplortCSVData()" id="btnMainLoginForm" value="Upload File" />
我的ng-files
的AngularJS指令是
app.directive('ngFiles', ['$parse', function ($parse) {
function fn_link(scope, element, attrs) {
var onChange = $parse(attrs.ngFiles);
element.on('change', function (event) {
onChange(scope, { $files: event.target.files });
});
};
return {
link: fn_link
}
}]);
我的AnagularJS控制器
app.controller('ProcessCSVController', function ($rootScope, $scope, HTTPService) {
$scope.CSVfile = {};
$scope.getTheFiles = function ($files) {
angular.forEach($files, function (value, key) {
$scope.CSVfile.append(key, value);
});
};
$scope.ImplortCSVData = function () {
HTTPService.uploadCSV($scope.CSVfile).then(function (result) {
alert("CSV");
});
}
});
我的HTTPService是
app.factory('HTTPService', function ($http, $q) {
formatCSV: function (_resultObj) {
var result = $http({
url: "localhost:8085/api/TAdmin/UploadCSVData",
method: 'POST',
data: _resultObj,
headers: {
"Content-Type": undefined
},
}).success(function (response) {
return {
errorCode: 0,
errorString: "",
result: response
}
}).error(function (error) {
return {
errorCode: 100,
errorString: "",
result: error
}
});
return result;
}
});
我的WebAPI C#代码
[HttpPost]
public HttpResponseMessage UploadCSVData(object csv)
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, csv);
var x = ms.ToArray();
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}