Angularjs将数据传递给Asp.Net Web api
本文关键字:Asp Net Web api 数据 Angularjs | 更新日期: 2023-09-27 18:07:02
我试图从angularjs ui导入文本文件,并将数据插入数据库。我可以导入文件和读取文件的内容。我还能够将数据插入到数据库与webapi。但是当我从UI传递数据到web api时,我被阻塞了。我不确定在这种情况下的问题是什么。我在这段代码中犯了什么错误?
UI代码<div>
<input type="file" id="file" name="file" />
<button ng-click="importMyData()">Import Configuration</button>
</div>
<div>
{{fileContent}}
</div>
Angular控制器代码
$scope.importMyData = function () {
var f = document.getElementById('file').files[0],
r = new FileReader();
r.onloadend = function (e) {
var binary = "";
var bytes = new Uint8Array(e.target.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
$scope.fileContent = (binary).toString();
importData($scope.fileContent);
}
r.readAsArrayBuffer(f);
}
function importData(fileContent) {
importConfigurationService.get({MyImportedData: fileContent}).$promise
.then(function (data) {
alert(data);
});
}
Angular Service代码
app.factory('importMyDataService', ['$resource', 'settings', function ($resource, settings) {
return $resource(settings.BaseSetting + '/api/ImportMyData');
}]);
Web Api代码
[Route("ImportMyData")]
[HttpGet]
public int ImportConfiguration(string MyImportedData)
{
string importedData = MyImportedData;
//Code to save imported data to db here
return importStatus;
}
我认为你需要使用MultipartMemoryStreamProvider
public class UploadingController : ApiController
{
public void Post()
{
if (Request.Content.IsMimeMultipartContent())
{
var streamProvider = new MultipartFormDataStreamProvider("c:/uploads/");
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
throw new HttpResponseException(HttpStatusCode.InternalServerError);
});
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
}
下面的文章应该会指引你正确的方向。
http://www.strathweb.com/2012/08/a-guide-to-asynchronous-file-uploads-in-asp-net-web-api-rtm/http://chris.59north.com/post/Uploading-files-using-ASPNET-Web-Api https://www.briankeating.net/post/Angularjs-NET-File-Upload